/**
 * 微信iDC商城
 * @module wechatMall/main
 * @author pmkx2 (185832959@qq.com)
 */
define('idc/main',
['jquery','storage','idc','bootstrap','lib/template','router','idc/data','idc/tpl','MD5','calendar','lib/artTemplate'], 
function($, Storage, Idc, bootstrap, Template, router, IdcData, tpl, MD5, calendar, artTemplate){
	var $body   = $('body');
	var $win    = $(window);
	var Idc 	= new Idc();		//IDC项目公用方法集
	var IdcData = new IdcData();	//数据操作
	var storage = new Storage();	//本地缓存
	var Loading = null;				//加载中方法
	var FnDate  = null;				//日期方法
	var nowDate = new Date();
	var status = false;             //判断是否有1200的限制
	var message = null;             //自由订单显示的提示内容
	var ArtTemplate = function( tpl, data ){
		return artTemplate.compile(tpl);
	};


	//产品列表
	var IdcWec = function( config ){
	    this.config = $.extend({
	        $root 		: $('body'),
	        shopId 		: '',				//店铺ID
	        dryDay		: 3,				//默认送货日：往后3天
	        source 		: 'WEC',			//订单来源：微信
	        userInfo 	: storage.get('_userInfo'),	//用户信息
	        imgUrl 		: 'http://www.synergyiclub.com:8086',	//图片地址
	        minPrice 	: 600,				//订单最少金额
	        maxPrice 	: 10000,			//订单最大上限金额（每日优选）
	       	minIndependentPrice : 900,		//订单最少金额：自由订单
	        /*
	        returnPriceProportion: [		//订单返利率
	    		{ price:9000, ptn:0.03, name:'3%' },
	    		{ price:8000, ptn:0.025, name:'2.5%' },
	    		{ price:7000, ptn:0.02, name:'2%' },
	    		{ price:6000, ptn:0.015, name:'1.5%' },
	    		{ price:5000, ptn:0.01, name:'1%' }
	    	]
	    	*/
	    	returnPriceProportion: [		//订单返利率
	    		{ price:900, ptn:0.03, name:'3%' },
	    		{ price:750, ptn:0.02, name:'2%' },
	    		{ price:600, ptn:0.01, name:'1%' }
	    	]
	    }, config || {});
	    //获取折扣率
		/*
		this.getPop = function( amount ){
    		var pop=0;//折扣
			if(amount>=9000){
				pop=0.03;
			}else if(amount>=8000){
				pop=0.025;
			}else if(amount>=7000){
				pop=0.02;
			}else if(amount>=6000){
				pop=0.015;
			}else if(amount>=5000){
				pop=0.01;
			}
			return pop;
    	}
    	*/
    	//获取折扣率
		this.getPop = function( amount ){
    		var pop=0;//折扣
			if(amount>=900){
				pop=0.03;
			}else if(amount>=750){
				pop=0.02;
			}else if(amount>=600){
				pop=0.01;
			}
			return pop;
    	}
		//页面
		this.$el = null;
		//当前路径
		this.nowPath = '';
		//页面名称
	    this.pageName = [
	    	'Welcome',				//欢迎页
	    	'Login',				//用户登录
	    	'Register',				//用户注册
	    	'PushGoods',			//推送订单
	    	'SmartOrder',			//智能订单
	    	'SubmitOrder',			//确认订单：推送订单
	    	'SubmitSmartOrder',		//确认订单：智能订单
	    	'UserCenter',			//个人中心
	    	'MyOrders',				//我的订单
	    	'OrdersDesc',			//订单详情
	    	'OrderListing',			//商品清单
	    	'SelectDate',			//选择日期
	    	'UpdatePushGoods',		//升级进货单
	    	'IndependentOrder',		//自由订单
	    	'SubmitIndependentOrder',	//确认订单：推送订单
	    	'Pay',					//支付
	    	'WebPay', 				//在线支付
	    	'Other'					//其他
	    ];
	    //下单过期时间
	    this.overdue = nowDate.getFullYear()+'-'+(nowDate.getMonth()+1)+'-'+nowDate.getDate()+' 17:00:00';
	    //日期：每日优选
	    this.pushGoodsDate = nowDate.getFullYear()+'-'+(nowDate.getMonth()+1)+'-'+nowDate.getDate();
	   	//日期：智能订单
	    this.smartOrderDate = nowDate.getFullYear()+'-'+(nowDate.getMonth()+1)+'-'+nowDate.getDate();
	    //临时用户每日优选：
	    this.tmpPushGoodsList = [];
	    //临时搜索商品列表
	    this.tmpSearchGoods = [];
	    //临时搜索商品列表：用户操作
	    this.tmpSearchGoodsSelect = [];
	  	//临时用户智能订单：确认信息
	    this.tmpSmartOrder = {};
	   	//临时用户每日优选：确认信息
	    this.tmpPushGoodsOrder = {};
	    //临时用户每日优选：当前勾选的商品
	    this.tmpCurrentPushGoods = {}
	    //临时用户每日优选：自由订单商品
	    this.tmpIndependentGoodsOrder = storage.get('_tmpIndependentGoodsOrder') || {};

	    //状态标识：加载中
	    this.loadingOrder = false;
	    //状态标识：提交中
	    this.senting = false;
	    //状态标识：是否修改过
	    this.isChange = false;
	    //状态标识：是否已生成一次
	    this.isBuilded = false;

	    //原始订单数据
    	this.OriginalRecommended = null;
	    //新订单数据
    	this.NewRecommended = null;
    	//优惠信息
    	this.discountInfo = null;
    	//返利率
    	this.returnPriceProportion = this.config.returnPriceProportion;
    	//搜索历史记录
    	this.searchHistory = [];
    	//搜索历史记录保存上限
    	this.searchHistoryLength = 20;

    	//加载中
    	this.loading = {};

	    //初始化
	    this.init();
	};

	//设置对应的页面
	IdcWec.prototype.setPage = function(callback){
		var self = this;
		router.route(':path', function(info){
			callback = callback || function(){};
			var pathname = info.pathname;
			//输入了错误版块时改变默认版块
			var truePage = 0;
			$.each(self.pageName,function(i,name){
				truePage += 1;
				if(pathname == name){
					self.nowPath = pathname;
					truePage = 0;
					return false;
				}
			});
			self.nowPath = truePage>0 ? 'Welcome' : self.nowPath;
			self.ant.set('nowPage', self.nowPath);
			self.ant.set('userInfo', self.config.userInfo);
			//读取对应的内容
			switch(pathname){
				//欢迎页
				case 'Welcome':
					self.loadWelcome(info);
					break;
				//用户登录
				case 'Login':
					self.loadLogin(info);
					break;
				//用户注册
				case 'Register':
					self.loadRegister(info);
					break;
				//每日优选
				case 'PushGoods':
					self.loadPushGoods(info);
					break;
				//智能订单
				case 'SmartOrder':
					self.loadSmartOrder(info);
					break;
				//自由订单
				case 'IndependentOrder':
					self.loadIndependentOrder(info);
					break;
				//确认订单：推送订单
				case 'SubmitOrder':
					self.loadSubmitOrder(info);
					break;
				//确认订单：智能订单
				case 'SubmitSmartOrder':
					self.loadSubmitSmartOrder(info);
					break;
				//确认订单：自由订单
				case 'SubmitIndependentOrder':
					self.loadSubmitIndependentOrder(info);
					break;
				//个人中心
				case 'UserCenter':
					self.loadUserCenter(info);
					break;
				//我的订单
				case 'MyOrders':
					self.loadMyOrders(info);
					break;
				//订单详情
				case 'OrdersDesc':
					self.loadOrdersDesc(info);
					break;
				//查看商品清单
				case 'OrderListing':
					self.loadOrderListing(info);
					break;
				//支付订单
				case 'Pay':
					self.loadPayOrder(info);
					break;
				//在线支付选择
				case 'WebPay':
					self.loadWebPay(info);
					break;
				//默认跳到欢迎页
				default:
					//window.location.href = '#Welcome';
					break;
			}
			callback();
		});
		router.start();
		if(window.location.href.indexOf('#') === -1){	//没有路由时，则改变路由
			window.location.href = window.location.href + '#Welcome';
		}
	};

//== 加载页面 =========================================================
	//欢迎页
	IdcWec.prototype.loadWelcome = function( info ){
		var self = this;
		self.isLogined();
		//关闭所有弹层
		self.hideCoverBox('#FirstMessage');
		self.hideCoverBox('#FirstIndependentMessage');
		//判断是否显示“智能推送”
		if(self.config['userInfo'] && self.config.userInfo.isShowRem == 1){
			self.ant.set('isShowRem',true);
		} else {
			self.ant.set('isShowRem',false);
		}
	};

	//用户登录
	IdcWec.prototype.loadLogin = function( info ){
		var self = this;
		if(info.query['id']){
			setTimeout(function(){
				var $UserName = self.$el.find('#UserLogin input[name="userName"]');
				$UserName.val(info.query['id']);
				alert('您已注册成功，请登录！');
			},500);
		}
	};

	//用户注册
	IdcWec.prototype.loadRegister = function( info ){
	};

	//每日优选
	IdcWec.prototype.loadPushGoods = function( info ){
		var self = this;
		self.isLogined(function(userInfo){
			self.pushGoodsDate = info.query.date || self.pushGoodsDate;
			var element = { shopId:self.config.shopId, date:self.pushGoodsDate };
			if(self.loadingOrder == false && (!info.query['event'] || info.query['event']!='sendPushOrder')){
				Loading.show();
				self.loadingOrder = true;
				//写入日期
				var $SelectDateInput = self.$el.find('#SelectDateInput');
				$SelectDateInput.val(self.pushGoodsDate);
				//获取优惠信息
				self.getDiscount(info, function(){
					//获取数据
					IdcData.getOrder(element,function(){},function(res){
						self.isChange = false;
						var goodsList = [];
						var allGoodsList = [];
						var todayPushGoodsOrder = {};
						var isHaveOrder = false;
						var canSubmitPushGoods = false;
						if(res.status==true){
							self.NewRecommended = self.OriginalRecommended = res;
							//修改每个商品的价格位数
							if(res.data!=null && res.data[0]){
								var data = res.data[0];
								//设置该推送订单折扣
								self.ant.set('pushGoodsDiscount',data.discount);
								self.ant.set('pushGoodsDiscountText',data.disWay);
								//重组商品
								var orderData = self.resetPushGoods(res);
								//判断是非已经提交过订单，1：为没有提交过订单，2：为提交过
								if(data.state == 1){
									$.each(data.order,function(i,o){
										$.each(o.goods,function(i2,o2){
											o2.prePrice = parseFloat(o2.prePrice==null ? 0 : o2.prePrice).toFixed(2);
											o2.price = parseFloat(o2.price==null ? 0 : o2.price).toFixed(2);
										});
									});
									//是否已提交订单
									//self.ant.set('isHaveOrder', false);
									//写入商品
									//self.ant.set('pushGoodList', orderData);
									//是否已提交订单
									isHaveOrder = false;
									//写入商品
									allGoodsList = orderData;
									var isOverdue = self.isOverdue(self.pushGoodsDate);
									//是否可提交订单
									//self.ant.set('canSubmitPushGoods', !isOverdue);
									canSubmitPushGoods = !isOverdue;
									//是否可升级进货单
									self.ant.set('canUpdatePushGoods', !isOverdue);
									//保存当前商品列表
									self.currentPushGoodsList = allGoodsList;
									//对商品进行分段
									$.each(allGoodsList, function(k,o){
										var gls = {
											index 	: o.index,
											type 	: o.type,
											typeId 	: o.typeId,
											goods 	: []
										};
										for(var i=0; i<10; i++){
											if(o.goods[i]){
												gls.goods.push(o.goods[i]);
											} else {
												break;
											}
										}
										goodsList.push(gls);
									});
								} else {
									var gl = [];
									//重组商品数据
									$.each(orderData,function(i,o){
										$.each(o.goods,function(i2,o2){
											gl.push({
												goodsNo		: o2.id,
												goodsName 	: o2.name,
												unit 		: o2.pkgUnit,
												spec 		: o2.spec,
												qty 		: o2.buyQty,
												price 		: o2.prePrice,
												disPrice 	: o2.price,	//折后价
												imgURL 		: o2.imgURL,
												subtotal	: o2.buyQty*o2.price
											});
										});
									});
									//写入数据
									todayPushGoodsOrder.orderInfo = data.orderInfo[0];
									todayPushGoodsOrder.goodsList = gl;
									//更改订单状态
									todayPushGoodsOrder.orderInfo.orderStatus = Idc.getOrderStateText(todayPushGoodsOrder.orderInfo.orderStatus);
									//更改支付方式文文字
									todayPushGoodsOrder.orderInfo.payWay = Idc.getPayWayText(todayPushGoodsOrder.orderInfo.payWay);
									//写入历史商品信息
									//self.ant.set('todayPushGoodsOrder', todayPushGoodsOrder);
									//写入缓存
									storage.set('_todayPushGoodsOrder', todayPushGoodsOrder);
									//如果今天已下单
									//self.ant.set('isHaveOrder', true);
									//是否可提交订单
									self.ant.set('canSubmitPushGoods', false);
									//是否可升级进货单
									//self.ant.set('canUpdatePushGoods', false;);
									//是否已提交订单
									isHaveOrder = true;
									//是否可提交订单
									canSubmitPushGoods = false;
								}
							}
							storage.set('_notNewUsers', self.config.userInfo.userId);
						} else {
							//是否可提交订单
							//self.ant.set('canSubmitPushGoods', false);
							//是否可升级进货单
							self.ant.set('canUpdatePushGoods', false);
							//是否已提交订单
							//self.ant.set('isHaveOrder', false);
							//写入空数据
							//self.ant.set('pushGoodList',false);
							//是否已提交订单
							isHaveOrder = false;
							//是否可提交订单
							canSubmitPushGoods = false;
						}
						//读取模版：每日优品内容
						var boxRender = ArtTemplate(tpl.pushGoodList.box);
				    	var boxHtml = boxRender({
					    		goodsList 			: goodsList,			//商品列表
					    		todayPushGoodsOrder : todayPushGoodsOrder,	//已下单信息
					    		isHaveOrder 		: isHaveOrder,			//是否已提交订单
					    		canSubmitPushGoods  : canSubmitPushGoods	//是否可提交订单
				    	});
						var $boxHtml = $(boxHtml);
						var $PushGoods = self.$el.find('#PushGoods');
						//改变类型分行
						var $types = $boxHtml.find('.goods-type a');
						$types.each(function(i,o){
							var $o = $(o);
							var tname = $o.text();
							if(tname.length > 2) {
								tname = tname.split('');
								tname.splice(2, 0, '<br>');
								tname = tname.join('');
								$o.html(tname);
							}
						});
						//写入模版
						$PushGoods.empty();
						$boxHtml.appendTo($PushGoods);
						//滚动加载数据
						if(goodsList.length>0){
							var $bdCont = $boxHtml.find('.bd-cont');
							$bdCont.scroll(function(){
								var $this = $(this);
								var $ul = $this.find('.product-list');
								if($this.scrollTop()>=(($ul.outerHeight()-$this.outerHeight())-150)){
									self.scrollAddPushGoods($this);
								}
							});
						}
						//设置每日优选公用元素
						self.idcElement().setPushOerderElm();
						//计算总价
						var tmpCurrentPushGoods = self.getTmpCurrentPushGoods();
						if(tmpCurrentPushGoods['date'] == self.pushGoodsDate){
							self.totalPushPrice(false, tmpCurrentPushGoods);
						} else {
							self.totalPushPrice();
						}
						//判断是否为新注册用户
						var notNewUsers = storage.get('_notNewUsers');
						if((!goodsList||goodsList.length==0) && !todayPushGoodsOrder['orderInfo'] && (!notNewUsers || notNewUsers!=self.config.userInfo.userId)){
							self.orderCountdown();
						}
						//取消加载中
						Loading.hide(0, function(){
							//显示第一次提示信息
							self.showMessage();
							self.loadingOrder = false;
						});
						//显示日期选项
						self.ant.set('pushGoodsDate',FnDate.getAllDate(self.pushGoodsDate));
						//清除过期订单的选择缓存
						self.emptyOverdueTmpCurrentPushGoods();
					});
				});
			}
		});
	};

	//智能订单
	IdcWec.prototype.loadSmartOrder = function( info ){
		var self = this;
		self.isLogined(function(userInfo){
			self.smartOrderDate = info.query.date || self.smartOrderDate;
			var element = { shopId:self.config.shopId, date:self.smartOrderDate };
			if(self.loadingOrder == false && (!info.query['event'] || info.query['event']!='sendSmartOrder')){
				Loading.show();
				self.loadingOrder = true;
				//写入日期
				var $SmartSelectDateInput = self.$el.find('#SmartSelectDateInput');
				$SmartSelectDateInput.val(self.smartOrderDate);
				//获取优惠信息
				self.getDiscount(info, function(){
					//获取数据
					IdcData.getSmartOrder(element,function(){},function(res){
						self.isChange = false;
						var goodsList = [];
						var allGoodsList = [];
						var todaySmartOrder = {};
						var isHaveOrder = false;
						var canSubmitSmartOrder = false;
						if(res.status==true){
							self.NewSmartOrderRecommended = self.OriginalSmartOrderRecommended = res;
							//修改每个商品的价格位数
							if(res.data!=null && res.data[0]){
								var data = res.data[0];
								//设置该推送订单折扣
								self.ant.set('smartOrderDiscount',data.discount);
								self.ant.set('smartOrderDiscountText',data.disWay);
								//重组商品
								var orderData = self.resetSmartGoods(res);
								//判断是非已经提交过订单，1：为没有提交过订单，2：为提交过
								if(data.state == 1){
									$.each(data.order,function(i,o){
										$.each(o.goods,function(i2,o2){
											o2.prePrice = parseFloat(o2.prePrice==null ? 0 : o2.prePrice).toFixed(2);
											o2.price = parseFloat(o2.price==null ? 0 : o2.price).toFixed(2);
										});
									});
									//是否已提交订单
									isHaveOrder = false;
									//写入商品
									allGoodsList = orderData;
									var isOverdue = self.isOverdue(self.smartOrderDate);
									canSubmitSmartOrder = !isOverdue;
									//保存当前商品列表
									self.currentSmartOrderList = allGoodsList;
									//对商品进行分段
									$.each(allGoodsList, function(k,o){
										var gls = {
											index 	: o.index,
											type 	: o.type,
											typeId 	: o.typeId,
											goods 	: []
										};
										for(var i=0; i<10; i++){
											if(o.goods[i]){
												gls.goods.push(o.goods[i]);
											} else {
												break;
											}
										}
										goodsList.push(gls);
									});
								} else {
									var gl = [];
									//重组商品数据
									$.each(orderData,function(i,o){
										$.each(o.goods,function(i2,o2){
											gl.push({
												goodsNo		: o2.id,
												goodsName 	: o2.name,
												unit 		: o2.pkgUnit,
												spec 		: o2.spec,
												qty 		: o2.buyQty,
												price 		: o2.prePrice,
												disPrice 	: o2.price,	//折后价
												imgURL 		: o2.imgURL,
												subtotal	: o2.buyQty*o2.price
											});
										});
									});
									//写入数据
									todaySmartOrder.orderInfo = data.orderInfo[0];
									todaySmartOrder.goodsList = gl;
									//更改订单状态
									todaySmartOrder.orderInfo.orderStatus = Idc.getOrderStateText(todaySmartOrder.orderInfo.orderStatus);
									//更改支付方式文文字
									todaySmartOrder.orderInfo.payWay = Idc.getPayWayText(todaySmartOrder.orderInfo.payWay);
									//写入缓存
									storage.set('_todaySmartOrder', todaySmartOrder);
									//是否可提交订单
									self.ant.set('canSubmitSmartOrder', false);
									//是否已提交订单
									isHaveOrder = true;
									//是否可提交订单
									canSubmitSmartOrder = false;
								}
							}
							storage.set('_notNewUsers', self.config.userInfo.userId);
						} else {
							//是否可升级进货单
							self.ant.set('canSubmitSmartOrder', false);
							//是否已提交订单
							isHaveOrder = false;
							//是否可提交订单
							canSubmitSmartOrder = false;
						}
						//读取模版：智能订单内容
						var boxRender = ArtTemplate(tpl.smartOrderList.box);
				    	var boxHtml = boxRender({
					    		goodsList 			: goodsList,			//商品列表
					    		todaySmartOrder 	: todaySmartOrder,		//已下单信息
					    		isHaveOrder 		: isHaveOrder,			//是否已提交订单
					    		canSubmitSmartOrder : canSubmitSmartOrder	//是否可提交订单
				    	});
						var $boxHtml = $(boxHtml);
						//改变类型分行
						var $types = $boxHtml.find('.goods-type a');
						$types.each(function(i,o){
							var $o = $(o);
							var tname = $o.text();
							if(tname.length > 2) {
								tname = tname.split('');
								tname.splice(2, 0, '<br>');
								tname = tname.join('');
								$o.html(tname);
							}
						});
						//写入模版
						var $SmartOrder = self.$el.find('#SmartOrder');
						$SmartOrder.empty();
						$boxHtml.appendTo($SmartOrder);
						//滚动加载数据
						/*if(goodsList.length>0){
							var $bdCont = $boxHtml.find('.bd-cont');
							$bdCont.scroll(function(){ 
								var $this = $(this);
								var $ul = $this.find('.product-list');
								if($this.scrollTop()>=(($ul.outerHeight()-$this.outerHeight())-150)){
									self.scrollAddSmartOrder($this, function(){
										self.totalSmartOrderPrice();
									});
								}
							});
							//检查商品库存
							*
							self.checkGoodsStock(function(stocks){
								if(stocks){
									console.log(stocks);
								}
							});
							*
						}*/
						//设置每日优选公用元素
						self.idcElement().setSmartOerderElm();
						//自动加载所有商品
						setTimeout(function(){
							self.autoAddSmartOrder(function(){
								//计算总价
								self.totalSmartOrderPrice();
							});
						},100);
						//判断是否为新注册用户
						var notNewUsers = storage.get('_notNewUsers');
						if((!goodsList||goodsList.length==0) && !todaySmartOrder['orderInfo'] && (!notNewUsers || notNewUsers!=self.config.userInfo.userId)){
							self.orderCountdown();
						}
						//取消加载中
						Loading.hide(0, function(){
							//显示第一次提示信息
							self.showMessage();
							self.loadingOrder = false;
						});
						//显示日期选项
						self.ant.set('smartOrderDate',FnDate.getAllDate(self.smartOrderDate));
					});
				});
			}
		});
	};

	//推荐商品
	IdcWec.prototype.loadRecommendGoods = function( typeId ){
		var self = this;
		//显示对应框
		self.showCoverBox('.update-push-goods');
		//是否能升级进货单
		var canUpdatePushGoods = self.ant.get('canUpdatePushGoods');
		if(self.loadingOrder === false && canUpdatePushGoods === true){
			//判断是否为对应日期的订单
			var $UpdatePushGoods = self.$el.find('#UpdatePushGoods');
			if($UpdatePushGoods.attr('data-date') !== self.pushGoodsDate){
				//开始查询
				var element = { shopId:self.config.shopId, date:self.pushGoodsDate };
				Loading.show();
				self.loadingOrder = true;
				IdcData.getRecommendedGoods(element,function(){},function(res){
					//重组商品
					var orderData = self.resetRecomGoods(res, typeId);
					//写入商品
					self.ant.set('recomProductList',orderData);
					//写入日期
					$UpdatePushGoods.attr('data-date', self.pushGoodsDate);
					//取消加载中
					Loading.hide(500, function(){
						//计算总价
						self.totalRecomPrice();
						self.loadingOrder = false;
					});
				});
			}
		}
	};

	//确认订单：推送订单
	IdcWec.prototype.loadSubmitOrder = function( info ){
	};

	//确认订单：智能订单
	IdcWec.prototype.loadSubmitSmartOrder = function( info ){
	};

	//确认订单：自由订单
	IdcWec.prototype.loadSubmitIndependentOrder = function( info ){
	};

	//个人中心
	IdcWec.prototype.loadUserCenter = function( info ){
		var self = this;
		self.isLogined(function(userInfo){
			//写入用户信息
			self.ant.set('userInfo', userInfo || []);
			Loading.show();
			Loading.hide();
		});
	};

	//我的订单
	IdcWec.prototype.loadMyOrders = function( info ){
		var self = this;
		self.isLogined(function(userInfo){
			//开始查询
			var element = { shopId:self.config.shopId, page:1, rp:300, type:'getHead' };
			if(self.loadingOrder == false){
				Loading.show();
				self.loadingOrder = true;
				IdcData.getOrdered(element,function(){},function(res){
					var pushGoodsOrdered = res;
					$.each(pushGoodsOrdered.rows||[],function(i,o){
						o.payType = Idc.getPayWayText(o.payType);
						if(o.plStatus=='E0021'){
							o.plStatusTxt = "待支付";
						}
					});
					//写入订单列表
					self.ant.set('pushGoodsOrdered',pushGoodsOrdered);
					//取消加载中
					Loading.hide(0, function(){
						//计算总价
						self.loadingOrder = false;
					});
				});
			}
		});
	};

	//订单详情
	IdcWec.prototype.loadOrdersDesc = function( info ){
		var self = this;
		self.isLogined(function(userInfo){
			//开始查询
			var element = { shopId:self.config.shopId, type:'getHead', orderId:info.query['orderId'] };
			if(self.loadingOrder == false){
				Loading.show();
				self.loadingOrder = true;
				var ordersDesc = {};
				//获取订单详细信息：信息
				IdcData.getOrdered(element,function(){},function(res){
					ordersDesc.allData = res.rows[0];
					ordersDesc.allData.phone = self.config.userInfo.telephone;
					ordersDesc.allData.address = self.config.userInfo.userAds;
					ordersDesc.allData.payType = Idc.getPayWayText(ordersDesc.allData.payType);
					//获取订单详细信息：商品
					element.type = 'getItem';
					IdcData.getOrdered(element,function(){},function(res2){
						var goodsList = [];
						//重组商品数据
						$.each(res2,function(i2,o2){
							goodsList.push({
								goodsNo		: o2.goodsIdRaw,
								goodsName 	: o2.goodsName,
								unit 		: o2.unitName,
								qty 		: o2.pliGoodsSum,
								price 		: o2.pliGoodsPrice,
								disPrice 	: o2.disPrice,	//折后价
								imgURL 		: self.config.imgUrl + o2.img,
								subtotal	: o2.pliGoodsSum
							});
						});
						//推荐订单 orderType=ZORA
						//自由订单 orderType=ZORB
						ordersDesc.goodsList = goodsList;
						//写入订单列表
						self.ant.set('ordersDesc', ordersDesc);
						//写入缓存
						storage.set('_ordersDescPushGoodsOrder', ordersDesc);
						//取消加载中
						Loading.hide(0, function(){
							//计算总价
							self.loadingOrder = false;
						});
					});
				});
			}
		});
	};

	//商品清单
	IdcWec.prototype.loadOrderListing = function( info ){
		var self = this;
		switch(info.query['form']){
			//页面来自于“智能订单：确认订单”
			case 'SubmitSmartOrder':
				self.ant.set('orderListing',storage.get('_tmpSmartOrder') || []);
				break;
			//页面来自于“每日优选：确认订单”
			case 'SubmitOrder':
				self.ant.set('orderListing',storage.get('_tmpPushGoodsOrder') || []);
				break;
			//页面来自于“自由订单：确认订单”
			case 'SubmitIndependentOrder':
				self.ant.set('orderListing',storage.get('_tmpIndependentGoodsOrderList') || []);
				break;
			//页面来自于“智能订单：确认订单”
			case 'HaveSmartOrder':
				self.ant.set('orderListing',storage.get('_todaySmartOrder') || []);
				break;
			//页面来自于“已有订单”
			case 'HaveOrder':
				self.ant.set('orderListing',storage.get('_todayPushGoodsOrder') || []);
				break;
			//页面来自于“订单详情”
			case 'OrdersDesc':
				self.ant.set('orderListing',storage.get('_ordersDescPushGoodsOrder') || []);
				break;
		}
	};

	//自由订单
	IdcWec.prototype.loadIndependentOrder = function( info ){
		var self = this;
		self.isLogined(function(userInfo){
			//开始查询
			if(self.loadingOrder == false){
				Loading.show();
				self.loadingOrder = true;
				IdcData.getLMCategory({},function(){},function(type){
					if(!type['code']){
						type = type || [];
						self.ant.set('LMCategory', type);
						self.loadingOrder = false;
						var firstTypeId = type.length > 0 ? type[0].categoryNoL : '';
						//获取商品
						self.getMallGoods({
							catNo: firstTypeId
						},function(){},function(){
							//计算临时商品总价
							self.totalIndependentPrice();
						});
					}
				});
			}
		});
	};

	//支付订单
	IdcWec.prototype.loadPayOrder = function( info ){
		var self = this;
		Loading.show();
		var orderId = info.query['orderId'];
		var price   = info.query['price'];
		var form    = info.query['form'];
		var devDay  = info.query['devDay'];
		$.ajax({
            url:'http://51xkh.com/wzf/servlet/Pay?order_id='+orderId,
            type:'POST', 
            success:function(res){
            	var begin = res.indexOf('<img');
            	var img = res.substring(begin, (res.indexOf('>', begin)+1));
            	var begin2 = img.indexOf('/wzf');
            	var qimgURL = 'http://51xkh.com'+img.substring(begin2, img.indexOf('"', begin2));
            	var payInfo = { type:'wechat', price:price, QRC:qimgURL, orderId:orderId };
            	Loading.hide(0,function(){
            		self.ant.set('payInfo', payInfo);
            	});
            }
        });
	};

	//在线支付方式
	IdcWec.prototype.loadWebPay = function( info ){
		var self = this;
		var orderId = info.query['orderId'];
		var price   = info.query['price'];
		Loading.hide(0,function(){
    		self.ant.set('webPayInfo', { orderId:orderId, price:price });
    	});
	};


//== 事件方法 =========================================================
	//判断用户是否登录过
	IdcWec.prototype.isLogined = function( callback ){
		var self = this;
		var user = self.config.userInfo;
		callback = callback || function(){};
		if(!user || user===false || user===null || user==='null' || !user['userId']){
			location.href = '#Login';
		} else {
			self.config.imgUrl = user.fileSerUrl;
			self.config.shopId = user.userId;
			callback(user);
		}
	};
	//用户登录
	IdcWec.prototype.login = function(){
		var self = this;
		var $UserLogin = self.$el.find('#UserLogin');
		var $userName = $UserLogin.find('input[name="userName"]');
		var $userPwd = $UserLogin.find('input[name="userPwd"]');
		var $viewBox = $UserLogin.find('.alt-box-view');
		IdcData.userLogin({
			userName: $userName.val(),
			userPwd: MD5($userPwd.val())
		},function(){},function(res){
			$viewBox.show().empty().append('<p class="alt-box bg-warning">登录中，请稍后...</p>');
			if(res['userId']){
				$UserLogin[0].reset();
				storage.set('_userInfo',res);
				self.config.userInfo = res;
				self.config.shopId = res.userId;
				$viewBox.show().empty().append('<p class="alt-box bg-success">登录成功！欢迎您：'+res.contact+'</p>');
				Loading.show('登录成功！');
				Loading.hide(3000,function(){
					$viewBox.show().empty();
					location.href = '#Welcome';
				});
			} else {
				$viewBox.show().empty().append('<p class="alt-box bg-danger">用户名或密码错误！</p>');
				setTimeout(function(){
					$viewBox.show().empty();
				},3000);
			}
		});
	};
	//注销用户
	IdcWec.prototype.logout = function(){
		var self = this;
		Loading.show('用户退出中...');
		Loading.hide(1000,function(){
			storage.remove('_userInfo');
			self.ant.set('userInfo', null);
			self.config.userInfo = null;
			self.config.shopId = '';
			self.discountInfo = null;
			//清除自由订单数据
			storage.remove('_tmpIndependentGoodsOrderList');
			storage.remove('_tmpIndependentGoodsOrder');
			storage.remove('tmpIndependentGoodsOrder');
			self.tmpIndependentGoodsOrder = {};
			//清除每日优选缓存
			self.emptySearchHistory();
			//转跳到登录页
			location.href = '#Login';
		});
	};

	//每日优选：添加推荐商品
	IdcWec.prototype.addMoreGoods = function(){
		var self = this;
		if(self.loadingOrder==false){
			var $bgCont = self.$el.find('#UpdatePushGoods .bd-cont');
			var $bgFirstUl = self.$el.find('#PushGoods .bd-cont.first .product-list');
			self.loadingOrder = true;
			//订单修改过
			self.isChange = true;
			Loading.show('添加到订单中...');
			$bgCont.each(function(c,cont){
				var $cont = $(cont);
				if(!$cont.hasClass('first')){
					var $goodsLi = $cont.find('li.user-selected');
					var $syncCont = self.$el.find('#PushGoods div[data-typeid="'+$cont.attr('data-typeid')+'"]');
					//循环添加
					$goodsLi.each(function(i,o){
						var $o = $(o);
						var $sync = $('#PushGoodLiType_'+$o.attr('data-id'));
						var $syncAll = $('#PushGoodLiAll_'+$o.attr('data-id'));
						if($sync.length>0){
							//有此商品则直接替换商品数量
							var $oNum = $o.find('.num');
							var $syncNum = $sync.find('.num');
							var $syncAllNum = $syncAll.find('.num');
							$sync.addClass('user-selected');
							$syncAll.addClass('user-selected');
							$syncNum.val($oNum.val()).removeAttr('disabled');
							$syncAllNum.val($oNum.val()).removeAttr('disabled');
						} else {
							//没有对应商品则新建一个对应的内容
							if($syncCont.length == 0){
								//没有该种类
								var $goodsTypeUl = self.$el.find('#PushGoods .goods-type');
								var $goodsList = self.$el.find('#PushGoods .goods-list');
								var $updataTypeLi = self.$el.find('#UpdatePushGoods .goods-type li[data-typeid="'+$cont.attr('data-typeid')+'"]');
								var $newTypeLi = $updataTypeLi.clone();
								$syncCont = $('<div class="bd-cont scroll-touch"></div>');
								//类型框赋值
								$newTypeLi.removeAttr('class');
								$newTypeLi.find('a').attr('data-index', $goodsTypeUl.find('li').length);
								//内容框赋值
								$syncCont.attr('data-index',$goodsList.find('.bd-cont').length);
								$syncCont.attr('data-typeid',$o.attr('data-typeid'));
								$syncCont.append('<ul class="product-list"></ul>');
								//添加
								$newTypeLi.appendTo($goodsTypeUl);
								$syncCont.appendTo($goodsList);
							}

							//没有该Ul标签
							var $newUl = null;
							if($syncCont.find('.product-list').length==0){
								$newUl = $('<ul class="product-list"></ul>');
								$syncCont.find('.prompt-msg').addClass('hide');
								$syncCont.prepend($newUl);
							} else {
								$newUl = $syncCont.find('.product-list');
							}

							//克隆商品
							var $newO1 = $o.clone();
							var $newO2 =  $o.clone();
							//添加到对应的分类框
							$newO1
								.attr('id','PushGoodLiType_'+$newO1.attr('data-id'))
								.attr('data-goodtype','og')
								.attr('data-ref','PushGoodLiAll_'+$newO1.attr('data-id'))
								.addClass('user-add');
							$newO1.find('.buy .num')
								.attr('id','PushGoodType_'+$newO1.attr('data-id'))
								.attr('data-ref','PushGoodAll_'+$newO1.attr('data-id'))
								.removeAttr('disabled');
							$newO1.appendTo($newUl);
							//添加到All的分类框
							$newO2
								.attr('id','PushGoodLiAll_'+$newO1.attr('data-id'))
								.attr('data-goodtype','og')
								.attr('data-ref','PushGoodLiType_'+$newO1.attr('data-id'))
								.addClass('user-add');
							$newO2.find('.buy .num')
								.attr('id','PushGoodAll_'+$newO1.attr('data-id'))
								.attr('data-ref','PushGoodType_'+$newO1.attr('data-id'))
								.removeAttr('disabled');
							$newO2.appendTo($bgFirstUl);

							//删除原有商品
							var $parUl = $o.parent();
							$o.remove();
							if($parUl.find('li').length){
								$parUl.hide().parent().append('<div class="prompt-msg">此品类下已没有商品</div>');
							}
						}
					});
				}
			});
			//计算订单总价和数量
			self.totalPushPrice(function(){
				//取消加载中
				Loading.hide(0, function(){
					self.loadingOrder = false;
					self.hideCoverBox('.update-push-goods');
				});
			});
		}
	};

	//自由订单，按条件获取商品（带默认操作）
	IdcWec.prototype.getMallGoods = function( element, beforeFn, backCallBack, callBack ){
		var self = this;
		if(self.loadingOrder == false){
			var isCache = false;	//是否要缓存
			Loading.show();
			self.loadingOrder = true;
			beforeFn = beforeFn || function(){};			//提交前操作
			backCallBack = backCallBack || function(){};	//默认操作后的回调函数
			callBack = callBack || function(res){			//默认操作
				//重排商品
					res.independStatus = self.status;
					res.indMessage = self.message;
					//res.msg = self.message;
					self.independentOrderGoodsList = {res:res, element:element};
					//数据分段
					var gl = {rows:[]};
					for(var i=0; i<10; i++){
						if(res.rows[i]){
							gl.rows.push(res.rows[i]);
						} else {
							break;
						}
					}
				var goodsList = self.resetMallGoods(gl, element);

                    $body.find('#tipsText').text(self.message);
					//$body.find('#indepenTips');
				//写入模版
				setTimeout(function(){
					//self.ant.set('independentOrderList', goodsList || []);
					//读取模版：自由订单内容（内容框）
					var boxRender = ArtTemplate(tpl.independentOrderList.box);
			    	var boxHtml = boxRender({ data: goodsList });
					var $boxHtml = $(boxHtml);
					if(goodsList.length>0){
			    		//读取模版：自由订单商品列表（选项）
						var itemRender = ArtTemplate(tpl.independentOrderList.item);
				    	var itemHtml = itemRender({ data: goodsList });
						var $itemHtml = $(itemHtml);
						$itemHtml.appendTo($boxHtml.find('ul'));
					}
					var $cont = self.$el.find('#IndependentOrder .goods-list');
					//添加到内容框
					$cont.empty();
					$boxHtml.appendTo($cont);
					//设置自由订单公用元素
					self.idcElement().setIndependentElm();
					//回调
					backCallBack();
					//滚动加载数据
					var $ul = $boxHtml.find('.product-list');
					$boxHtml.scroll(function(){
						if($boxHtml.scrollTop()>=(($ul.outerHeight()-$boxHtml.outerHeight())-150)){
							self.scrollAddIndependentGoods($boxHtml);
						}
					});
					if(res.length <= 10){
						$boxHtml.find('.loading-data').addClass('hide');
					}
					//取消加载中
					Loading.hide(0, function(){
						//显示第一次提示信息
						//self.showMessage('FirstIndependentMessage');
						self.loadingOrder = false;
					});
				},(isCache ? 100 : 0));
			};
			var offsetTop = "80px";
			//判断商品类型ID是否为33
			if(element && element['catNo'] && element['catNo']==33){
				element.type='tm';
				self.ant.set('monthTime', true);
				$body.find('#MonthTime').text('全部剩余效期');
				offsetTop = "130px"
			} else {
				self.ant.set('monthTime', false);
			}
			$body.find('#IndependentOrder .view-box-container').css({'top':offsetTop});
			//$body.find('#indepenTips')
			//获取用户是否有1200的限制
			var ele = {shopId:self.config.shopId};
			IdcData.isExistDelivery(ele,beforeFn, function (data) {
				self.status = data.status;
				self.message = data.msg;
				//取商品信息
				IdcData.getMallGoods(element, beforeFn, function(res){
					callBack(res)
				},isCache);
			});

		}
	};

	//自由订单，按剩余效期获取商品
	IdcWec.prototype.getTimeMallGoods = function( element, beforeFn, backCallBack, callBack ){
		var self = this;
		if(self.loadingOrder == false){
			var isCache = false;	//是否要缓存
			Loading.show();
			self.loadingOrder = true;
			//获取时间
			if(element && element['month']){
				var month = element['month']=='null' ? 'null' : parseInt(element['month'])*30;
				var date = month=='null' ? '' : (FnDate.getDirDate(month)).date;
				element = { type:'tm', catNo:33, beginDate:date };
			} else {
				element = { type:'tm', catNo:33, beginDate:'' };
			}
			//方法设置
			beforeFn = beforeFn || function(){};			//提交前操作
			backCallBack = backCallBack || function(){};	//默认操作后的回调函数
			callBack = callBack || function(res){			//默认操作
				//重排商品
				res = self.resortMallGoods(res);
				//保存所有数据
				self.independentOrderGoodsList = {res:res, element:element};
				//数据分段
				var gl = {rows:[]};
				for(var i=0; i<10; i++){
					if(res.rows[i]){
						gl.rows.push(res.rows[i]);
					} else {
						break;
					}
				}
				var goodsList = self.resetMallGoods(gl, element);
				//写入模版
				setTimeout(function(){
					//读取模版：自由订单内容（内容框）
					var boxRender = ArtTemplate(tpl.independentOrderList.box);
			    	var boxHtml = boxRender({ data: goodsList });
					var $boxHtml = $(boxHtml);
					if(goodsList.length>0){
			    		//读取模版：自由订单商品列表（选项）
						var itemRender = ArtTemplate(tpl.independentOrderList.item);
				    	var itemHtml = itemRender({ data: goodsList });
						var $itemHtml = $(itemHtml);
						$itemHtml.appendTo($boxHtml.find('ul'));
					}
					var $cont = self.$el.find('#IndependentOrder .goods-list');
					$cont.empty();
					$boxHtml.appendTo($cont);
					//设置自由订单公用元素
					self.idcElement().setIndependentElm();
					//回调
					backCallBack();
					//滚动加载数据
					var $ul = $boxHtml.find('.product-list');
					$boxHtml.scroll(function(){
						if($boxHtml.scrollTop()>=(($ul.outerHeight()-$boxHtml.outerHeight())-150)){
							self.scrollAddIndependentGoods($boxHtml);
						}
					});
					if(res.length <= 10){
						$boxHtml.find('.loading-data').addClass('hide');
					}
					//取消加载中
					Loading.hide(0, function(){
						self.loadingOrder = false;
					});
				},(isCache ? 100 : 0));
			};
			//取商品信息
			IdcData.getMallGoods(element, beforeFn, function(res){
				callBack(res)
			},isCache);
		}
	};

	//自由订单，按名称搜索商品（带默认操作）
	IdcWec.prototype.searchMallGoods = function( element, beforeFn, backCallBack, callBack ){
		var self = this;
		if(element['goodsName'] && element['goodsName']!==''){
			if(self.loadingOrder == false){
				Loading.show();
				self.loadingOrder = true;
				beforeFn = beforeFn || function(){};			//提交前操作
				self.ant.set('showSearchHistory', false);
				backCallBack = backCallBack || function(){};	//默认操作后的回调函数
				if(!element['catNo'] || (element['catNo'] && element['catNo']=='99999')){
					element.catNo = '';
				}
				callBack = callBack || function(res){			//默认操作
					var goodsList = self.tmpSearchGoods = self.resetMallGoods(res);
					//读取模版：自由订单搜索商品列表（内容框）
					var boxRender = ArtTemplate(tpl.searchIndependentGoodsList.box);
			    	var boxHtml = boxRender({ data: goodsList });
					var $boxHtml = $(boxHtml);
			    	if(goodsList.length>0){
			    		//读取模版：自由订单搜索商品列表（选项）
						var itemRender = ArtTemplate(tpl.searchIndependentGoodsList.item);
				    	var itemHtml = itemRender({ data: goodsList });
						var $itemHtml = $(itemHtml);
						$itemHtml.appendTo($boxHtml);
						//保存搜索信息到本地缓存
						self.addSearchHistory(element.catNo, element.goodsName);
					}
					//添加到目标DOM中
					var $cont = self.$el.find('#SearchIndependentGoods .goods-list .bd-cont');
					$cont.empty();
					$boxHtml.appendTo($cont);
					//回调
					backCallBack();
					//取消加载中
					Loading.hide(0, function(){
						//显示第一次提示信息
						self.loadingOrder = false;
					});
				};
				//取商品信息
				IdcData.searchMallGoods(element, beforeFn, function(res){
					callBack(res)
				});
			}
		} else {
			alert('搜索内容不能为空');
		}
	};

	//智能订单：重组智能订单商品列表
	IdcWec.prototype.resetSmartGoods = function( res ){
		var self = this;
		var orderData = [];
		if(res.data!=null && res.data.length>0){
			$.each(res.data[0].order || [],function(i,o){
				$.each(o.goods,function(i2,o2){
					//改变图片地址：判断图片是否为 null
					o2.imgURL = (o2.imgURL==null||o2.imgURL=='null') ? './images/def.jpg' : (self.config.imgUrl+o2.imgURL);
					//添加状态：是否为新增
					o2.goodStu = '';
					o2.state = true;
				});
				//追加index
				o.index = i;
			});
			orderData = res.data[0].order;
		}
		return orderData;
	};

	//每日优选：重组推送订单商品列表
	IdcWec.prototype.resetPushGoods = function( res ){
		var self = this;
		var orderData = [];
		if(res.data!=null && res.data.length>0){
			//判断当前商品列表是否有历史操作
			var currentGoods = null;
			var tmpCurrentPushGoods = self.getTmpCurrentPushGoods();
			if(tmpCurrentPushGoods['date'] && tmpCurrentPushGoods['goodsList']){
				if(res.data[0].date === tmpCurrentPushGoods.date){
					currentGoods = tmpCurrentPushGoods.goodsList;
					self.isChange = true;
				}
			}
			//生成所有商品
			var all = { type:'全部', typeId:'99999', index:0, goods:[] };
			$.each(res.data[0].order || [],function(i,o){
				$.each(o.goods,function(i2,o2){
					//改变图片地址：判断图片是否为 null
					o2.imgURL = (o2.imgURL==null||o2.imgURL=='null') ? './images/def.jpg' : (self.config.imgUrl+o2.imgURL);
					o2.state = true;		//是否为可选商品，false为不可选
					//将商品添加到“All”之下
					//all.goods.push(o2);
					//添加状态：是否为新增
					o2.goodStu = '';
					o2.selected = false;	//商品是否有选中
					o2.qty = 1;				//初始数量
					//判断当前是否有选中日期
					if(currentGoods && currentGoods[o2.id]){
						var cg = currentGoods[o2.id];
						o2.selected = true;
						o2.qty = cg.qty;
					}
				});
				//追加index
				o.index = i;
			});
			//res.data[0].order.unshift(all);
			orderData = res.data[0].order;
		}
		return orderData;
	};

	//每日优选：重组推荐商品列表
	IdcWec.prototype.resetRecomGoods = function( res ){
		var self = this;
		var orderData = [];
		if(res.data!=null && res.data.length>0){
			//生成所有商品
			var all = { type:'全部', typeId:'99999', index:0, goods:[] };
			$.each(res.data || [],function(i,o){
				$.each(o.goods,function(i2,o2){
					//改变图片地址：判断图片是否为 null
					o2.imgURL = (o2.imgURL==null||o2.imgURL=='null') ? './images/def.jpg' : (self.config.imgUrl+o2.imgURL);
					//添加状态：是否为新增
					o2.goodStu = 'recom';
					o2.state = true;
					//将商品添加到“All”之下
					all.goods.push(o2);
				});
				//追加index
				o.index = i+1;
			});
			res.data.unshift(all);
			orderData = res.data;
		}
		return orderData;
	};

	//自由订单：重组商品列表
	IdcWec.prototype.resetMallGoods = function( res, element, removeSelected ){
		var self = this;
		var orderData = [];
		var tigo = self.tmpIndependentGoodsOrder;
		var goodsList = tigo['goodsList'] ? tigo['goodsList'] : {};
		element = element || {};
		self.tmpSearchGoodsDefSelect = false;	//是否有默认选中商品
		if(res.rows!=null && res.rows.length>0){
			var qtyZeroList = [];
			var qtyNotZeroList = [];
			$.each(res.rows || [],function(i,o){
				var goods = goodsList[o.goodsNo];
				//改变图片地址：判断图片是否为 null
				o.bigImgUrl = (o.bigImgUrl==null||o.bigImgUrl=='null') ? './images/def.jpg' : (self.config.imgUrl+o.bigImgUrl);
				//追加index
				o.index = 1;
				o.nowQty = 0;
				o.price = parseFloat(o.price).toFixed(2);
				o.userSelected = false; 
				o.catNoId = element['catNo'] ? element.catNo : '';
				if(goods){
					o.userSelected = goods.qty>0 ? true : false;
					o.nowQty = goods.qty;
					self.tmpSearchGoodsDefSelect = true;
				}
				//库存量为0时，则为false
				o.state = o.stockQty>0 ? true : false;
				//判断是否清除已选中的
				if(removeSelected == true){
					if(o.userSelected != true){
						//分离数组
						//o.stockQty>0 ? qtyNotZeroList.push(o) : qtyZeroList.push(o);
						orderData.push(o);
					}
				} else {
					//分离数组
					//o.stockQty>0 ? qtyNotZeroList.push(o) : qtyZeroList.push(o);
					orderData.push(o);
				}
			});
			//orderData = orderData.concat(qtyNotZeroList);
			//orderData = orderData.concat(qtyZeroList);
		}
		return orderData;
	};

	//自由订单：重新排序商品
	IdcWec.prototype.resortMallGoods = function( res, element ){
		if(res.rows!=null && res.rows.length>0){
			var orderData = [];
			var qtyZeroList = [];
			var qtyNotZeroList = [];
			$.each(res.rows || [],function(i,o){
				orderData.push(o);
				//分离数组
				//o.stockQty>0 ? qtyNotZeroList.push(o) : qtyZeroList.push(o);
			});
			//orderData = orderData.concat(qtyNotZeroList);
			//orderData = orderData.concat(qtyZeroList);
			res.rows = orderData;
		}
		return res;
	};

	//智能订单：提交订单
	IdcWec.prototype.sendSmartOrder = function(){
		var self = this;
		if(self.senting == false){
			self.senting = true;
			Loading.show('订单提交中...');
			//重新获取需提交的内容
			var tmpSmartOrder = storage.get('_tmpSmartOrder');
			var payWay = self.$el.find('#SubmitSmartOrder input[name="payWay"]:checked').val();	//支付方式
			tmpSmartOrder.allData.payWay = payWay;
			tmpSmartOrder.orderInfo = 'json='+JSON.stringify(tmpSmartOrder.allData);
			//提交订单
			IdcData.sendOrder(tmpSmartOrder.orderInfo,function(){},function(res){
				self.senting = false;
				if(res.code==2000){
					Loading.show('订单提交成功！');
					setTimeout(function(){
						location.href = '#SmartOrder?date='+tmpSmartOrder.allData.deliveryDate;
						//location.href='#OrdersDesc?orderId='+res.msg;
					},4000);
					//订单修改过
					self.isChange = false;
				} else {
					Loading.show('订单提交失败！');
					Loading.hide(3000);
				}
			});
		}
	};

	//每日优选：提交订单
	IdcWec.prototype.sendPushGoodsOrder = function(){
		var self = this;
		if(self.senting == false){
			self.senting = true;
			Loading.show('订单提交中...');
			//重新获取需提交的内容
			var tmpPushGoodsOrder = storage.get('_tmpPushGoodsOrder');
			var payWay = self.$el.find('#SubmitOrder input[name="payWay"]:checked').val();	//支付方式
			tmpPushGoodsOrder.allData.payWay = payWay;
			tmpPushGoodsOrder.orderInfo = 'json='+JSON.stringify(tmpPushGoodsOrder.allData);
			//提交订单
			IdcData.sendOrder(tmpPushGoodsOrder.orderInfo,function(){},function(res){
				self.senting = false;
				if(res.code==2000){
					Loading.show('订单提交成功！');
					setTimeout(function(){
						if(payWay=='SMW6'){
							//location.href='#Pay?orderId='+res.msg+'&price='+tmpPushGoodsOrder.allData.amount;
							location.href='#WebPay?orderId='+res.msg+'&price='+tmpPushGoodsOrder.allData.amount;
						} else {
							location.href = '#PushGoods?date='+tmpPushGoodsOrder.allData.deliveryDate;
						}
					},4000);
					//订单修改过
					self.isChange = false;
					//清空当前勾选商品列表
					self.emptyTmpCurrentPushGoods();
				} else {
					Loading.show('订单提交失败！');
					Loading.hide(3000);
				}
			});
		}
	};

	//自由订单：提交订单
	IdcWec.prototype.sendIndependentGoodsOrder = function(){
		var self = this;
		if(self.senting == false){
			self.senting = true;
			Loading.show('订单提交中...');
			//重新获取需提交的内容
			var tmpIndependentGoodsOrderList = storage.get('_tmpIndependentGoodsOrderList');
			var payWay = self.$el.find('#SubmitIndependentOrder input[name="payWay"]:checked').val();	//支付方式
			tmpIndependentGoodsOrderList.allData.payWay = payWay;
			tmpIndependentGoodsOrderList.orderInfo = 'json='+JSON.stringify(tmpIndependentGoodsOrderList.allData);
			//提交订单
			IdcData.sendIndependentOrder(tmpIndependentGoodsOrderList.orderInfo,function(){},function(res){
				self.senting = false;
				if(res.code == 1005){
					Loading.hide(3000);
					alert("有的商品库存不足，请重新选择，替换库存不足的商品！");
					var data = res.data;
					var old = self.tmpIndependentGoodsOrder;
					var goodList = old.goodsList;

					console.log("data: "+JSON.stringify(data));
					for(var i = 0; i < data.length;i++){
						var aa = data[i];
						goodList[aa.goodsNo].qty=aa.stockQty;
						//alert("no: "+aa.goodsNo+" qty: "+aa.stockQty);
					}
					self.getIndependentOrderPreview();
					self.showCoverBox('#IndependentOrderPreview');
					storage.set('_tmpIndependentGoodsOrder', self.tmpIndependentGoodsOrder);
				}else if(res.code==2000){
					Loading.show('订单提交成功！');
					//清除数据
					storage.remove('_tmpIndependentGoodsOrderList');
					storage.remove('_tmpIndependentGoodsOrder');
					storage.remove('tmpIndependentGoodsOrder');
					self.tmpIndependentGoodsOrder = {};
					setTimeout(function(){
						if(payWay=='SMW6'){
							location.href='#WebPay?orderId='+res.msg+'&price='+tmpIndependentGoodsOrderList.allData.amount;
						} else {
							location.href = '#MyOrders';
							setTimeout(function(){
								var $back = self.$el.find('a[href="#back"]');
								$back.attr('data-gotoPage','#IndependentOrder');
								$back.attr('data-isOne','true');
							},500);
						}
						//location.href='#OrdersDesc?orderId='+res.msg;
					},4000);
				} else {
					Loading.show('订单提交失败！');
					Loading.hide(3000);
				}
			});
		}
	};

	//智能订单：取消智能订单
	IdcWec.prototype.cancelSmartOrder = function( orderId, devDay ){
		var self = this;
		if(self.senting == false){
			self.senting = true;
			Loading.show('订单取消中...');
			var element = { forecastId:orderId, shopId:self.config.shopId, devDay:devDay, remark:'' };
			//取消订单
			IdcData.cancelRecommendedOrder(element,function(){},function(res){
				self.senting = false;
				switch(res.code){
					//取消成功
					case 2000:
						Loading.show('订单取消成功！');
						setTimeout(function(){
							location.href = '#SmartOrder?date='+devDay;
						},3000);
						break;
					//取消成功
					case 1003:
						Loading.show('订单已被取消！');
						Loading.hide(3000);
						break;
				}
			});
		}
	};

	//每日优选：取消推送订单
	IdcWec.prototype.cancelRecommendedOrder = function( orderId, devDay ){
		var self = this;
		if(self.senting == false){
			self.senting = true;
			Loading.show('订单取消中...');
			var element = { forecastId:orderId, shopId:self.config.shopId, devDay:devDay, remark:'' };
			//取消订单
			IdcData.cancelRecommendedOrder(element,function(){},function(res){
				self.senting = false;
				switch(res.code){
					//取消成功
					case 2000:
						Loading.show('订单取消成功！');
						setTimeout(function(){
							location.href = '#PushGoods';
						},3000);
						break;
					//取消成功
					case 1003:
						Loading.show('订单已被取消！');
						Loading.hide(3000);
						break;
				}
			});
		}
	};

	//IDC：加载时定义初始使用的元素
	IdcWec.prototype.idcElement = function( ){
		var self = this;
		var elm = {
			//每日优选
			setSmartOerderElm : function( callback ){
				callback = callback || function(){};
				var $SO = $body.find('#SmartOrder');
				self.$AllSmartOrderSku 			= $SO.find('#AllSmartOrderSku');			//总商品数
				self.$TotalSmartOrderPrice 		= $SO.find('#TotalSmartOrderPrice');		//总价钱
				self.$TotalSmartOrderPriceOG 	= $SO.find('#TotalSmartOrderPriceOG');		//原价
				self.$ReturnSmartOrderPrice 	= $SO.find('#ReturnSmartOrderPrice');		//返利
				self.$CumulativeSmartOrderPrice = $SO.find('#CumulativeSmartOrderPrice');	//7天累计金额
				callback();
			},
			//每日优选
			setPushOerderElm : function( callback ){
				callback = callback || function(){};
				var $PG = $body.find('#PushGoods');
				self.$AllPushSku 		= $PG.find('#AllPushSku');			//总商品数
				self.$TotalPushPrice 	= $PG.find('#TotalPushPrice');		//总价钱
				self.$TotalPushPriceOG 	= $PG.find('#TotalPushPriceOG');	//原价
				self.$ReturnPrice 		= $PG.find('#ReturnPrice');			//返利
				self.$CumulativePrice 	= $PG.find('#CumulativePrice');		//7天累计金额
				callback();
			},
			//自由订单
			setIndependentElm : function( callback ){
				callback = callback || function(){};
				var $IO = $body.find('#IndependentOrder');
				self.$AllIndependentSku 	= $IO.find('#AllIndependentSku');		//总商品数
				self.$TotalIndependentPrice = $IO.find('#TotalIndependentPrice');	//总价钱
				callback();
			},
			//自由订单：订单预览
			setIndependentPreviewElm : function( callback ){
				callback = callback || function(){};
				var $IOP = $body.find('#IndependentOrderPreview');
				self.$IndependentOrderPreviewPrice = $IOP.find('#IndependentOrderPreviewPrice');	//订单预览总价
				callback();
			}
		};
		return elm;
	};

	//智能推送：计算总价
	IdcWec.prototype.totalSmartOrderPrice = function( callBack ){
		var self = this;
		var callBack = callBack || function(){};
		var smartOrderDiscount 	= self.ant.get('smartOrderDiscount');			//折扣
		var $allPro = $body.find('#SmartOrder .bd-cont li.user-selected .num');	//所有选中的商品
		//获取数量与总价
		var totalprice 		= 0;
		var totalpriceOG 	= 0;
		var returnPrice 	= 0;
		var cumulativePrice = 0;
		$allPro.each(function(i,o){
			var $o = $(o);
			var pnum = parseInt($o.val());
			totalprice += (pnum*parseFloat($o.attr('data-preprice')));
			totalpriceOG += (pnum*parseFloat($o.attr('data-price')));
		});
		//计算优惠信息
		var di = self.discountInfo;
		var tmp = di.curAmount + totalprice;		//总金额加销售金额
		pop = self.getPop(tmp);						//取得折扣率
		returnPrice = di.lastAmount + tmp * pop;	//获取真实折扣金额
		//7天累计金额
		cumulativePrice = totalprice + di.curAmount;
		if(di.flag==0){
			totalprice = (totalprice-di.lastAmount)<0 ? 0 : (totalprice-di.lastAmount);
		}
		//用户下第七天的订单，并且是本周期最后单，计算本周期折扣
		else if(di.flag==1){
			var tmp = di.curAmount + totalprice;		//总金额加销售金额
			pop = self.getPop(tmp);						//取得折扣率
			totalprice = (totalprice-(di.lastAmount+tmp*pop))<0 ? 0 : (totalprice-(di.lastAmount+tmp*pop));
		}
		//赋值
		self.$AllSmartOrderSku.text($allPro.length);						//总sku数
		self.$TotalSmartOrderPrice.text(totalpriceOG.toFixed(2));				//当前返利后的金额
		self.$TotalSmartOrderPriceOG.text(totalpriceOG.toFixed(2));			//本次订单金额
		self.$ReturnSmartOrderPrice.text(0);			//返利金额
		self.$CumulativeSmartOrderPrice.text(0);	//7天累计金额
		callBack();
	};

	//每日优选：计算总价
	IdcWec.prototype.totalPushPrice = function( callBack, order ){
		var self = this;
		var callBack = callBack || function(){};
		var pushGoodsDiscount 	= self.ant.get('pushGoodsDiscount');			//折扣
		//获取数量与总价
		var totalprice 		= 0;
		var totalpriceOG 	= 0;
		var returnPrice 	= 0;
		var cumulativePrice = 0;
		var allSku 			= 0;
		//判断是否为有商品对象列表，如果没有，则从当前页面中查找
		if(typeof order !== 'object'){
			var $allPro = $body.find('#PushGoods .bd-cont li.user-selected .num');	//所有选中的商品
			$allPro.each(function(i,o){
				var $o = $(o);
				var pnum = parseInt($o.val());
				totalprice += (pnum*parseFloat($o.attr('data-preprice')));
				totalpriceOG += (pnum*parseFloat($o.attr('data-price')));
			});
			allSku = $allPro.length;
		} else {
			//此商品列表格式以 _tmpCurrentPushGoods 为准
			if(order['goodsList']){
				$.each(order.goodsList || [],function(k, o){
					var pnum = parseInt(o.qty);
					totalprice += (pnum*parseFloat(o.disPrice));
					totalpriceOG += (pnum*parseFloat(o.price));
					allSku++;
				});
			}
		}
		//计算优惠信息
		//var di = self.discountInfo;
		/*if(di.flag==0){
			returnPrice = di.lastAmount;
		}
		//用户下第七天的订单，并且是本周期最后单，计算本周期折扣
		else if(di.flag==1){
			var tmp = di.curAmount + totalprice;		//总金额加销售金额
			pop = self.getPop(tmp);						//取得折扣率

		}*/
		/*
		var tmp = di.curAmount + totalprice;		//总金额加销售金额
		pop = self.getPop(tmp);						//取得折扣率
		returnPrice = di.lastAmount + tmp * pop;	//获取真实折扣金额
		//下次可返利
		cumulativePrice = totalprice + di.curAmount;
		*/
		//cumulativePrice = totalprice + (self.discountInfo.flag==1 ? self.discountInfo.curAmount : self.discountInfo.lastAmount);
		//计算折扣
		//totalprice = totalprice * pushGoodsDiscount;
		//计算返利率
		/*
		$.each(self.returnPriceProportion, function(i, o){
			if(cumulativePrice >= o.price){
				returnPrice = cumulativePrice * o.ptn;
				return false;
			}
		});
		*/
		/*
		if(di.flag==0){
			//returnPrice = di.lastAmount;
			totalprice = (totalprice-di.lastAmount)<0 ? 0 : (totalprice-di.lastAmount);
		}
		//用户下第七天的订单，并且是本周期最后单，计算本周期折扣
		else if(di.flag==1){
			var tmp = di.curAmount + totalprice;		//总金额加销售金额
			pop = self.getPop(tmp);						//取得折扣率
			totalprice = (totalprice-(di.lastAmount+tmp*pop))<0 ? 0 : (totalprice-(di.lastAmount+tmp*pop));
		}
		*/
		//totalprice = (totalprice-returnPrice)<0 ? 0 : (totalprice-returnPrice);


		// -- 3月30日计算方式 ------------------------------------------------------------
		//计算优惠信息
		var di 			= self.discountInfo;					//折扣信息
		returnPrice 	= di.integral>300 ? 300 : di.integral;
		totalprice 		= (totalprice-returnPrice)>0 ? totalprice-returnPrice : 0;				//实付款
		cumulativePrice = totalprice * self.getPop(totalprice);	//下次可返利
		cumulativePrice = cumulativePrice>300 ? 300 : cumulativePrice;

		//赋值
		self.$AllPushSku.text(allSku);							//总sku数
		self.$TotalPushPrice.text(totalprice.toFixed(2));		//实付款
		self.$TotalPushPriceOG.text(totalpriceOG.toFixed(2));	//本次订单金额
		self.$ReturnPrice.text(returnPrice.toFixed(2));			//可用返利金额
		self.$CumulativePrice.text(cumulativePrice.toFixed(2));	//下次可返利
		callBack(totalprice);
	};

	//推荐商品：计算总价
	IdcWec.prototype.totalRecomPrice = function( callBack ){
		var self = this;
		var callBack = callBack || function(){};
		var $el 				= self.$el;
		var $AllRecomSku 		= $el.find('#AllRecomSku');					//总商品数
		var $TotalRecomPrice 	= $el.find('#TotalRecomPrice');				//总价钱
		var $TotalRecomPriceOG 	= $el.find('#TotalRecomPriceOG');			//原价钱
		var $allPro 			= $el.find('#UpdatePushGoods .bd-cont.first li.user-selected .num');	//所有选中的商品
		var pushGoodsDiscount 	= self.ant.get('pushGoodsDiscount');		//折扣
		//获取数量与总价
		var totalprice = 0;
		var totalpriceOG = 0;
		$allPro.each(function(i,o){
			var $o = $(o);
			var pnum = parseInt($o.val());
			totalprice += (pnum*parseFloat($o.attr('data-price')));
			totalpriceOG += (pnum*parseFloat($o.attr('data-price')));
		});
		//计算折扣
		totalprice = totalprice * pushGoodsDiscount;
		//赋值
		$AllRecomSku.text($allPro.length);
		$TotalRecomPrice.text(totalprice.toFixed(2));
		$TotalRecomPriceOG.text(totalpriceOG.toFixed(2));
		callBack();
	};

	//自由订单：计算总价
	IdcWec.prototype.totalIndependentPrice = function( callBack ){
		var self = this;
		var callBack = callBack || function(){};
		var tigo = self.tmpIndependentGoodsOrder;							//临时商品列表信息
		//获取数量与总价
		var sku = 0;
		var totalprice = 0.00;
		if(tigo['goodsList']){
			var i = 0;
			$.each(tigo.goodsList, function(k, o){
				o.subtotal = parseFloat(o.qty*o.disPrice).toFixed(2);
				totalprice += parseFloat(o.subtotal); //叠加价格
				i++;
			});
			sku = i;
		}
		//赋值
		self.$AllIndependentSku.text(sku);
		self.$TotalIndependentPrice.text(totalprice.toFixed(2));
		callBack();
		return { sku:sku, totalprice:totalprice.toFixed(2) };
	};

	//每日优选：按指定或上下天数取订单
	IdcWec.prototype.getPrevNextOrder = function( PN ){
		var self = this;
		//是否可提交订单
		var canSubmitPushGoods = self.ant.get('canSubmitPushGoods');
		var nowChange = true;
		if(self.isChange==true && canSubmitPushGoods==true){
			var result = confirm('你的推荐订单修改过，你确认要离开吗？');  
			if(!result){
				nowChange = false;
			}
		}
		//是否可离开
		if(nowChange == true){
			if(self.loadingOrder==false && self.senting==false){
				var $date = self.$el.find('.date-title .date');
				//获取标题日期并生成对应的日期
				var dirs = PN==='prev' ? -1 : 1;
				var pgd = FnDate.getDirDate(dirs, self.pushGoodsDate);
				//写入日期
				self.ant.set('pushGoodsDate',pgd);
				location.href='#PushGoods?date='+pgd.date;
			}
		}
	};

	//智能订单：按指定或上下天数取订单
	IdcWec.prototype.getSmartPrevNextOrder = function( PN ){
		var self = this;
		//是否可提交订单
		var canSubmitSmartOrder = self.ant.get('canSubmitSmartOrder');
		var nowChange = true;
		if(self.isChange==true && canSubmitSmartOrder==true){
			var result = confirm('你的推荐订单修改过，你确认要离开吗？');  
			if(!result){
				nowChange = false;
			}
		}
		//是否可离开
		if(nowChange == true){
			if(self.loadingOrder==false && self.senting==false){
				var $date = self.$el.find('.date-title .date');
				//获取标题日期并生成对应的日期
				var dirs = PN==='prev' ? -1 : 1;
				var pgd = FnDate.getDirDate(dirs, self.smartOrderDate);
				//写入日期
				self.ant.set('smartOrderDate',pgd);
				location.href='#SmartOrder?date='+pgd.date;
			}
		}
	};

	//每日优选：显示选择日期框
	IdcWec.prototype.showSelectDate = function( ){
		var self = this;
		var $SelectDateInput = self.$el.find('#SelectDateInput');
		//显示选择框
		self.showCoverBox('.select-date');
		//展开日期插件
		$SelectDateInput.focus();
	};

	//智能订单：显示选择日期框
	IdcWec.prototype.showSmartSelectDate = function( ){
		var self = this;
		var $SmartSelectDateInput = self.$el.find('#SmartSelectDateInput');
		//显示选择框
		self.showCoverBox('.smart-select-date');
		//展开日期插件
		$SmartSelectDateInput.focus();
	};

	//每日优选：保存商品勾选临时列表
	IdcWec.prototype.saveTmpCurrentPushGoods = function( $elm, id, qty ){
		var self = this;
		var goodsId;
		var orderItem;
		var pgd = self.getDateNum();
		//获取所有缓存
		var tmpCurrentPushGoods = storage.get('_tmpCurrentPushGoods') || {};
		var allTcpg = tmpCurrentPushGoods['allTcpg'] ? tmpCurrentPushGoods['allTcpg'] : {};
		var tcpg = allTcpg[pgd] ? allTcpg[pgd] : {};

		if(tcpg['date'] != self.pushGoodsDate){
			tcpg = {};
		}
		//判断是否有商品列表
		tcpg.goodsList = tcpg['goodsList'] ? tcpg['goodsList'] : {};
		//循环读取商品明细
		if(typeof $elm === 'object'){
			var $li = $elm.parents('li');
			var $o = $li.find('.num');
			goodsId = $o.attr('data-id');
			//获取商品信息
			orderItem = self.getItemData($o);
			//判断是否为选中商品
			tcpg.goodsList[goodsId] = $li.hasClass('user-selected') ? orderItem : null;
		} else {
			goodsId = id;
			orderItem = tcpg.goodsList[goodsId];
			orderItem.qty = parseInt(qty);
			//判断商品数量是否为0
			tcpg.goodsList[goodsId] = orderItem.qty ? orderItem : null;
		}

		//重组列表
		var tmpGoodsList = {};
		var length = 0;
		$.each(tcpg.goodsList, function(k, o){
			if(o != null){
				tmpGoodsList[k] = o;
				length++;
			}
		});
		tcpg.date = self.pushGoodsDate;
		tcpg.goodsList = tmpGoodsList;
		tcpg.length = length;
		tcpg.dateNum = parseInt(pgd);

		allTcpg[pgd] = tcpg;
		tmpCurrentPushGoods.allTcpg = allTcpg;

		//保存商品列表
		self.tmpCurrentPushGoods = tmpCurrentPushGoods;
		storage.set('_tmpCurrentPushGoods', self.tmpCurrentPushGoods);
		return tcpg;
	};

	//每日优选：获取商品勾选临时列表
	IdcWec.prototype.getTmpCurrentPushGoods = function( date ){
		var pgd = this.getDateNum(date);
		var tmpCurrentPushGoods = this.tmpCurrentPushGoods = storage.get('_tmpCurrentPushGoods') || {};
		var allTcpg = tmpCurrentPushGoods['allTcpg'] ? tmpCurrentPushGoods['allTcpg'] : {};
		return allTcpg[pgd] ? allTcpg[pgd] : {};
	};

	//每日优选：清空指定日期商品勾选临时列表
	IdcWec.prototype.emptyTmpCurrentPushGoods = function( date ){
		var self = this;
		var pgd = self.getDateNum(date);
		var tcpg = null;
		var tmpCurrentPushGoods = self.tmpCurrentPushGoods;
		if(tmpCurrentPushGoods['allTcpg']){
			var allTcpg = tmpCurrentPushGoods.allTcpg;
			if(allTcpg[pgd]){
				//删除对应数据
				tcpg = allTcpg[pgd];
				delete allTcpg[pgd];
				//保存缓存数据
				tmpCurrentPushGoods.allTcpg = allTcpg;
				self.tmpCurrentPushGoods = tmpCurrentPushGoods;
				storage.set('_tmpCurrentPushGoods', self.tmpCurrentPushGoods);
			}
		}
		return tcpg;
	};

	//每日优选：清空过期订单的商品勾选临时列表
	IdcWec.prototype.emptyOverdueTmpCurrentPushGoods = function( date ){
		var self = this;
		var tmpCurrentPushGoods = storage.get('_tmpCurrentPushGoods') || {};
		var allTcpg = tmpCurrentPushGoods['allTcpg'] ? tmpCurrentPushGoods['allTcpg'] : {};
		var dryDate = FnDate.getDirDate(self.config.dryDay);
		var overdueDate = self.getDateNum(dryDate.date);
		$.each(allTcpg || [], function(k,o){
			if(parseInt(k) < overdueDate){
				delete allTcpg[k];
			}
		});
		//保存缓存数据
		tmpCurrentPushGoods.allTcpg = allTcpg;
		self.tmpCurrentPushGoods = tmpCurrentPushGoods;
		storage.set('_tmpCurrentPushGoods', self.tmpCurrentPushGoods);
	};

	//每日优选：清空所有商品勾选临时列表
	IdcWec.prototype.emptyAllTmpCurrentPushGoods = function(){
		this.tmpCurrentPushGoods = {};
		return storage.remove('_tmpCurrentPushGoods');
	};

	//每日优选：获取日期短号码
	IdcWec.prototype.getDateNum = function( date ){
		date = date || this.pushGoodsDate;
		var pgd = date.split('-');
		pgd.map(function(d,i){
			pgd[i] = parseInt(d)<10 ? ('0'+d) : d;
		});
		pgd = pgd.join('');
		return parseInt(pgd);
	};

	//自由订单：保存商品临时列表
	IdcWec.prototype.saveTmpIndependentGoods = function( $elm ){
		var self = this;
		var tigo = storage.get('_tmpIndependentGoodsOrder') || {};
		//循环读取商品明细
		if(typeof $elm === 'object'){
			var $li = $elm.parents('li');
			var $o = $li.find('.num');
			var goodsId = $o.attr('data-id');
			//获取商品信息
			var orderItem = self.getItemData($o);
			//判断是否有商品列表
			tigo.goodsList = tigo['goodsList'] ? tigo['goodsList'] : {};
			//判断是否为选中商品
			tigo.goodsList[goodsId] = $li.hasClass('user-selected') ? orderItem : null;
			//重组列表
			var tmpGoodsList = {};
			$.each(tigo.goodsList, function(k, o){
				if(o != null){
					tmpGoodsList[k] = o;
				}
			});
			tigo.goodsList = tmpGoodsList;
			//保存商品列表
			self.tmpIndependentGoodsOrder = tigo;
			storage.set('_tmpIndependentGoodsOrder', self.tmpIndependentGoodsOrder);
		}
	};

	//自由订单：判断搜索框内是否有选中商品
	IdcWec.prototype.checkSearchGoods = function( $elm ){
		var self = this;
		var id = $elm.attr('data-id');
		var tsgs = self.tmpSearchGoodsSelect;	//用户临时选择商品
		if(tsgs.indexOf(id) == -1){
			tsgs.push(id);
		}
		var $AddToIndependentGoods = self.$el.find('#AddToIndependentGoods');
		//判断是否有修改过
		if(tsgs.length > 0){
			var $selectedGoods = self.$el.find('#SearchIndependentGoods .bd-cont .user-selected');
			if(self.tmpSearchGoodsDefSelect==true){
				if($selectedGoods.length>0){
					$AddToIndependentGoods.removeClass('disabled');
				} else {
					$AddToIndependentGoods.text('保存').removeClass('disabled');
				}
			} else {
				if($selectedGoods.length>0){
					$AddToIndependentGoods.removeClass('disabled');
				} else {
					$AddToIndependentGoods.addClass('disabled');
				}
			}
		} else {
			$AddToIndependentGoods.addClass('disabled');
		}
	};

	//自由订单：显示商品搜索框
	IdcWec.prototype.showSearchIndependentGoods = function(){
		var self = this;
		self.tmpSearchGoodsSelect = [];			//用户临时选择商品重置为0
		self.tmpSearchGoodsDefSelect = false;	//是否有默认选中商品
		var $cont = self.$el.find('#SearchIndependentGoods .bd-cont');
		var $SearchIndependentText = self.$el.find('#SearchIndependentText');
		var $AddToIndependentGoods = self.$el.find('#AddToIndependentGoods');
		$cont.empty().html('<div class="prompt-msg">点击“搜索”显示结果</div>');
		$SearchIndependentText.val('');
		$AddToIndependentGoods.text('添加到购物车').addClass('disabled');
		self.showCoverBox('#SearchIndependentGoods');	//显示搜索框
		self.ant.set('showSearchHistory',true);
		self.loadSearchHistory();	//加载搜索历史记录
	};

	//自由订单：隐藏商品搜索框
	IdcWec.prototype.hideSearchIndependentGoods = function(){
		var self = this;
		self.hideCoverBox('#SearchIndependentGoods');
	};

	//自由订单：添加搜索商品到购物车中
	IdcWec.prototype.addToIndependentGoods = function(){
		var self = this;
		var $cont = self.$el.find('#SearchIndependentGoods .bd-cont');
		//var $selectedGoods = $cont.find('.user-selected');
		var tsgs = self.tmpSearchGoodsSelect;
		//循环读取商品明细
		if(tsgs.length > 0){
			Loading.show();
			var tigo = storage.get('_tmpIndependentGoodsOrder') || {};
			//判断是否有商品列表
			tigo.goodsList = tigo['goodsList'] ? tigo['goodsList'] : {};
			//循环添加商品
			$.each(tsgs,function(i, o){
				var $li = $body.find('#SearchIndependentGoodLiType_'+o);
				if($li.length>0){
					var $o = $li.find('.num');
					var goodsId = $o.attr('data-id');
					//获取商品信息
					var orderItem = self.getItemData($o);
					//列表中是否存在此商品
					if(!tigo.goodsList[goodsId]){
						if(orderItem.qty>0){
							//判断是否为选中商品
							tigo.goodsList[goodsId] = orderItem;
						}
					} else {
						//判断商品是否为选择
						if($li.hasClass('user-selected')){
							//判断是否为选中商品
							tigo.goodsList[goodsId] = orderItem;
						} else {
							tigo.goodsList[goodsId] = null;
						}
					}
					//重组列表
					var tmpGoodsList = {};
					$.each(tigo.goodsList, function(k, o){
						if(o != null){
							tmpGoodsList[k] = o;
						}
					});
					tigo.goodsList = tmpGoodsList;
					//把当前显示的商品状态改变
					var $LinkGoods = self.$el.find('#IndependentOrderGoodLiType_'+goodsId);
					if($LinkGoods.length>0){
						var $LinkGoodsNum = $LinkGoods.find('.num');
						if($li.hasClass('user-selected')){
							$LinkGoods.addClass('user-selected');
							$LinkGoodsNum.val($o.val()).removeAttr('disabled');
						} else {
							$LinkGoods.removeClass('user-selected');
							$LinkGoodsNum.val($o.val()).attr('disabled',true);
						}
					}
					//保存商品列表
					self.tmpIndependentGoodsOrder = tigo;
					storage.set('_tmpIndependentGoodsOrder', self.tmpIndependentGoodsOrder);
					//重新计算总价
					self.totalIndependentPrice();
				}
			});
			Loading.hide(0,function(){
				//关闭搜索框
				self.hideCoverBox('#SearchIndependentGoods');
			});
		}
	};

	//自由订单：加载搜索历史记录
	IdcWec.prototype.loadSearchHistory = function( ){
		var self = this;
		//self.emptySearchHistory();
		$('#NowSearchType').text('全部分类').attr('data-typeid','99999');
		self.searchHistory = storage.get('searchHistory') || [];
		self.ant.set('searchHistory', self.searchHistory);
	};

	//自由订单：添加搜索历史记录
	IdcWec.prototype.addSearchHistory = function( typeid, goodsName ){
		var self = this;
		var sh = self.searchHistory || [];
		var index = null;
		$.each(sh,function(i,o){
			if(o.goodsName===goodsName){
				index = i;
				return false;
			}
		});
		//console.log('index:'+index+'  '+typeid+':'+goodsName);
		if(index==null) {
			sh.splice(0, 0, {typeId:typeid, goodsName:goodsName});
		} else {
			sh.splice(index, 1);
			sh.splice(0, 0, {typeId:typeid, goodsName:goodsName});
		}
		//消除上限外关键词
		if(sh.length > self.searchHistoryLength){
			sh.pop();
		}
		storage.set('searchHistory', sh);
	};

	//自由订单：清空搜索历史记录
	IdcWec.prototype.emptySearchHistory = function( ){
		var self = this;
		self.searchHistory = [];
		storage.remove('searchHistory');
		self.ant.set('searchHistory',null);
	};

	//每日优选：改变商品选中状态
	//$elm：元素对象；   type：操作方式（1为加减，2为是否选中））
	IdcWec.prototype.changeChecked = function( $elm, type ){
		var self = this;
		var goodType = $elm.attr('data-goodtype');
		//订单修改过
		self.isChange = true;
		switch(goodType){
			//计算推送订单总价：智能推送
			case 'smart':
				//显示推荐数量
				var $li = $elm.parents('li');
				var $num = $li.find('.num');
				var saleVol = $num.attr('data-saleVol');
				var val = $num.val();
				if(saleVol != val){
					$li.find('.recom').removeClass('hide');
				}
				//计算总价
				self.totalSmartOrderPrice(); 
				break;
			//计算推送订单总价：每日优选
			case 'og':
				//保存当前商品勾选列表 并 计算总价
				//self.totalPushPrice(false, self.saveTmpCurrentPushGoods($elm));
				//重新计算总价
				self.totalPushPrice(function(price){
					//判断是否超出订单额度上限
					if(price > self.config.maxPrice){
						alert('单张订单金额上限为￥10000');
						if(type===1){
							var $num = $elm.parent().find('.num');
							var oldQty = $num.attr('data-qty');
							$num.val(oldQty).attr('data-qty',oldQty);
							self.totalPushPrice(false, self.saveTmpCurrentPushGoods(false, $num.attr('data-id'), oldQty));
						} else if(type===2){
							var $li = $elm.parent();
							var $num = $li.find('.num');
							$li.removeClass('user-selected');
							self.totalPushPrice(false, self.saveTmpCurrentPushGoods(false, $num.attr('data-id'), oldQty));
						}
					}
				}, self.saveTmpCurrentPushGoods($elm));
				break;
			//计算推荐商品总价：推荐商品
			case 'recom': self.totalRecomPrice(); break;
			//计算自由订单商品总价：自由订单
			case 'independent':
				//保存商品临时列表
				self.saveTmpIndependentGoods($elm);
				//计算总价
				self.totalIndependentPrice();
				break;
			//计算自由订单商品总价：自由订单（商品搜索）
			case 'search': 
				//检查是否有选中商品
				self.checkSearchGoods($elm);
			break;
		}
	};

	//智能订单：生成订单数据(确认订单)
	IdcWec.prototype.smartOrderSubmit = function(){
		var self = this;
		var $allPro = self.$el.find('#SmartOrder .bd-cont li.user-selected .num');	//所有选中的商品
		if($allPro.length>0){
			Loading.show('订单生成中...');
			var $AllSmartOrderSku = self.$el.find('#AllSmartOrderSku');							//总商品数
			var $TotalSmartOrderPrice = self.$el.find('#TotalSmartOrderPrice');					//折扣价
			var $TotalSmartOrderPriceOG = self.$el.find('#TotalSmartOrderPriceOG');				//总价钱
			var payWay = self.$el.find('#SubmitSmartOrder input[name="payWay"]:checked').val();		//支付方式
			if(parseInt($TotalSmartOrderPrice.text()) >= self.config.minPrice){
				var nowHref = window.location.href;
				if(nowHref.indexOf('sendSmartOrder') == -1){
					window.location.href = nowHref + (nowHref.indexOf('date')==-1 ? '?':'&') + 'event=sendSmartOrder';
				}
				//循环读取商品明细
				var goodsList = [];
				var goodsItems = [];
				$allPro.each(function(i,o){
					var $o = $(o);
					var orderItem = {};
					var itemInfo = {};
					orderItem.goodsNo 	= itemInfo.goodsNo		= $o.attr('data-id');
					orderItem.goodsName = null;	//订单json中的商品名称改为null
					itemInfo.goodsName  = $o.attr('data-goodsName');
					orderItem.unit 		= itemInfo.unit 		= $o.attr('data-unit');
					orderItem.spec 		= itemInfo.spec 		= $o.attr('data-spec');
					orderItem.qty 		= itemInfo.qty 			= parseInt($o.val());
					orderItem.price 	= itemInfo.price 		= parseFloat($o.attr('data-preprice'));	//原价
					orderItem.disPrice 	= itemInfo.disPrice 	= parseFloat($o.attr('data-price'));	//折后价
					orderItem.subtotal 	= itemInfo.subtotal		= orderItem.qty*orderItem.disPrice;
					goodsItems.push(orderItem);
					//保存临时商品清单
					itemInfo.imgURL = $o.attr('data-imgUrl');
					goodsList.push(itemInfo);
				});
				//生成订单信息
				var us = self.config.userInfo;
				var isDiscount = 'N';
				if(parseFloat($TotalSmartOrderPrice.text())<parseFloat($TotalSmartOrderPriceOG.text())){
					isDiscount = 'Y';
				}
				var allData = {
					'userId'		: us.userId,				//店铺编号
					'userName'		: us.userName,				//店铺名称
					'contact'		: us.contact,				//联系人
					'phone'			: us.phone,					//联系电话
					'telephone'		: us.telephone,				//联系电话2
					'amount'		: $TotalSmartOrderPrice.text(),	//订单金额
					'forecastId'	: self.OriginalSmartOrderRecommended.data[0].forecastId,	//推荐订单号
					'source'		: self.config.source,		//订单来源
					'delivery'		: us.userAds,				//门店地址
					'isPaid'		: '0',						//是否支付
					'payWay'		: payWay,					//支付方式
					'deliveryDate'	: self.smartOrderDate,		//送货日期
					'isDiscount'	: isDiscount,				//是否打折
					'orderType'		: 'remo',					//智能订单标识
					'items'			: goodsItems				//商品明细
				};
				//保存信息
				self.tmpSmartOrder.allData = allData;
				self.tmpSmartOrder.goodsList = goodsList;
				self.tmpSmartOrder.orderInfo = 'json='+JSON.stringify(allData);
				//写入缓存
				storage.set('_tmpSmartOrder', self.tmpSmartOrder);
				//写入临时订单信息
				self.ant.set('tmpSmartOrder', self.tmpSmartOrder);
				Loading.hide(500,function(){
					//转跳到订单确认页面
					window.location.href = '#SubmitSmartOrder';
				});
			} else {
				Loading.hide(0,function(){
					alert('最低配送金额为'+self.config.minPrice+'元，无法确认订单！');
				});
			}
		} else {
			Loading.hide(0,function(){
				alert('您还没有选择商品，无法确认订单！');
			});
		}
	};

	//每日优选：生成订单数据(确认订单)
	IdcWec.prototype.pushGoodsSubmit = function(){
		var self = this;
		var tmpCurrentPushGoods = self.tmpCurrentPushGoods;
		if(tmpCurrentPushGoods['goodsList'] && tmpCurrentPushGoods.length>0){
			Loading.show('订单生成中...');
			var $AllPushSku = self.$el.find('#AllPushSku');							//总商品数
			var $TotalPushPrice = self.$el.find('#TotalPushPrice');					//折扣价
			var $TotalPushPriceOG = self.$el.find('#TotalPushPriceOG');				//总价钱
			var payWay = self.$el.find('#SubmitOrder input[name="payWay"]:checked').val();	//支付方式
			if(parseInt($TotalPushPriceOG.text()) >= self.config.minPrice){
				var nowHref = window.location.href;
				if(nowHref.indexOf('sendPushOrder') == -1){
					window.location.href = nowHref + (nowHref.indexOf('date')==-1 ? '?':'&') + 'event=sendPushOrder';
				}
				//循环读取商品明细
				var goodsList = [];
				var goodsItems = [];
				var allPro = tmpCurrentPushGoods.goodsList;
				$.each(allPro, function(i,o){
					var orderItem = {};
					var itemInfo = {};
					orderItem.goodsNo 	= itemInfo.goodsNo		= o.goodsNo;
					orderItem.goodsName = null;	//订单json中的商品名称改为null
					itemInfo.goodsName  = o.goodsName;
					orderItem.unit 		= itemInfo.unit 		= o.unit;
					orderItem.spec 		= itemInfo.spec 		= o.spec;
					orderItem.qty 		= itemInfo.qty 			= parseInt(o.qty);
					orderItem.price 	= itemInfo.price 		= parseFloat(o.price);	//原价
					orderItem.disPrice 	= itemInfo.disPrice 	= parseFloat(o.disPrice);	//折后价
					orderItem.subtotal 	= itemInfo.subtotal		= orderItem.qty*orderItem.disPrice;
					goodsItems.push(orderItem);
					//保存临时商品清单
					itemInfo.imgURL = o.imgUrl;
					goodsList.push(itemInfo);
				});
				//生成订单信息
				var us = self.config.userInfo;
				var isDiscount = 'N';
				if(parseFloat($TotalPushPrice.text())<parseFloat($TotalPushPriceOG.text())){
					isDiscount = 'Y';
				}
				var allData = {
					'userId'		: us.userId,				//店铺编号
					'userName'		: us.userName,				//店铺名称
					'contact'		: us.contact,				//联系人
					'phone'			: us.phone,					//联系电话
					'telephone'		: us.telephone,				//联系电话2
					'amount'		: $TotalPushPrice.text(),	//订单金额
					'forecastId'	: self.OriginalRecommended.data[0].forecastId,	//推荐订单号
					'source'		: self.config.source,		//订单来源
					'delivery'		: us.userAds,				//门店地址
					'isPaid'		: '0',						//是否支付
					'payWay'		: payWay,					//支付方式
					'deliveryDate'	: self.pushGoodsDate,		//送货日期
					'orderFrom'		: self.discountInfo.orderFrom,	//
					'isDiscount'	: isDiscount,				//是否打折
					'items'			: goodsItems				//商品明细
				};
				//保存信息
				self.tmpPushGoodsOrder.allData = allData;
				self.tmpPushGoodsOrder.goodsList = goodsList;
				self.tmpPushGoodsOrder.orderInfo = 'json='+JSON.stringify(allData);
				//写入缓存
				storage.set('_tmpPushGoodsOrder', self.tmpPushGoodsOrder);
				//写入临时订单信息
				self.ant.set('tmpPushGoodsOrder', self.tmpPushGoodsOrder);
				Loading.hide(500,function(){
					//转跳到订单确认页面
					window.location.href = '#SubmitOrder';
				});
			} else {
				Loading.hide(0,function(){
					alert('最低配送金额为'+self.config.minPrice+'元，无法确认订单！');
				});
			}
		} else {
			Loading.hide(0,function(){
				alert('您还没有选择商品，无法确认订单！');
			});
		}
	};

	//自由订单：生成订单数据(确认订单)
	IdcWec.prototype.independentOrderSubmit = function(){
		var self = this;
		var tigo = self.tmpIndependentGoodsOrder;	//所有选中的商品
		if(tigo['goodsList']){
			Loading.show('订单生成中...');
			var $AllIndependentSku = self.$el.find('#AllIndependentSku');				//总商品数
			var $TotalIndependentPrice = self.$el.find('#TotalIndependentPrice');		//折扣价
			var payWay = self.$el.find('#SubmitIndependentOrder input[name="payWay"]:checked').val();	//支付方式
			if(parseInt($TotalIndependentPrice.text()) >= self.config.minIndependentPrice || self.status){
				//循环读取商品明细
				var goodsList   = [];
				var goodsItems  = [];
				var qtyZeroList = [];	//QTY为0的商品
				var deliveryDate = self.getIndependentDeliveryDate();
				$.each(tigo.goodsList, function(k,o){
					var orderItem = {};
					var itemInfo  = {};
					if(o!=null){
						var qty = parseInt(o.qty);
						if(qty>0){
							orderItem.goodsName = null;	//订单json中的商品名称改为null
							itemInfo.goodsName 	= o.goodsName;
							orderItem.goodsNo 	= itemInfo.goodsNo		= o.goodsNo;
							orderItem.unit 		= itemInfo.unit 		= o.unit;
							orderItem.spec 		= itemInfo.spec 		= o.spec;
							orderItem.qty 		= itemInfo.qty 			= o.qty;
							orderItem.stockQty 	= itemInfo.stockQty		= o.stockQty;
							orderItem.price 	= itemInfo.price 		= o.price;		//原价
							orderItem.disPrice 	= itemInfo.disPrice 	= o.disPrice;	//折后价
							orderItem.subtotal 	= itemInfo.subtotal		= o.subtotal;
							goodsItems.push(orderItem);
							//保存临时商品清单
							itemInfo.imgURL = o.imgUrl;
							goodsList.push(itemInfo);
						} else {
							qtyZeroList.push(o);
						}
					}
				});
				//生成订单信息
				var us = self.config.userInfo;
				var allData = {
					'userId'	: us.userId,				//店铺编号
					'userName'	: us.userName,				//店铺名称
					'contact'	: us.contact,				//联系人
					'phone'		: us.phone,					//联系电话
					'telephone'	: us.telephone,				//联系电话2
					'amount'	: $TotalIndependentPrice.text(),	//订单金额
					'source'	: self.config.source,		//订单来源
					'delivery'	: us.userAds,				//门店地址
					'deliveryDate' : deliveryDate,			//送货日期
					'isPaid'	: '0',						//是否支付
					'payWay'	: payWay,					//支付方式
					'items'		: goodsItems				//商品明细
				};
				//保存信息
				self.tmpIndependentGoodsOrder.allData = allData;
				self.tmpIndependentGoodsOrder.orderInfo = 'json='+JSON.stringify(allData);
				//写入缓存
				storage.set('_tmpIndependentGoodsOrder', self.tmpIndependentGoodsOrder);
				storage.set('_tmpIndependentGoodsOrderList', { allData:allData, goodsList:goodsList });
				//写入临时订单信息
				self.ant.set('tmpIndependentGoodsOrder', { allData:allData, goodsList:goodsList });
				Loading.hide(500,function(){
					//转跳到订单确认页面
					window.location.href = '#SubmitIndependentOrder';
					if(qtyZeroList.length>0){
						var name = '';
						$.each(qtyZeroList,function(i,o){
							name += o.goodsName+'\n';
						});
						setTimeout(function(){
							alert('以下商品提交失败，因为商品数为0：\n'+name);
						},500);
					}
				});
			} else {
				Loading.hide(0,function(){
					alert('最低配送金额为'+self.config.minIndependentPrice+'元，无法确认订单！');
				});
			}
		} else {
			Loading.hide(0,function(){
				alert('您还没有选择商品，无法确认订单！');
			});
		}
	};

	//智能订单：订单预览
	IdcWec.prototype.getSmartOrderPreview = function(){
		var self = this;
		Loading.show('预览生成中...');
		var $allPro = self.$el.find('#SmartOrder .bd-cont li.user-selected .num');	//所有选中的商品
		var $AllSmartOrderSku = self.$el.find('#AllSmartOrderSku');					//总商品数
		var $TotalSmartOrderPrice = self.$el.find('#TotalSmartOrderPrice');			//折扣价
		var $TotalSmartOrderPriceOG = self.$el.find('#TotalSmartOrderPriceOG');		//总价钱
		var $ReturnSmartOrderPrice = self.$el.find('#ReturnSmartOrderPrice');		//返利
		//循环读取商品明细
		var goodsList = [];
		$allPro.each(function(i,o){
			var orderItem = self.getItemData($(o));
			goodsList.push(orderItem);
		});
		//生成订单信息
		var allData = {
			'allPushSku'		: $AllSmartOrderSku.text(),			//总商品数
			'totalPushPrice'	: $TotalSmartOrderPrice.text(),		//实付款
			'totalPushPriceOG'	: $TotalSmartOrderPriceOG.text(),	//订单总额
			'returnPrice'		: $ReturnSmartOrderPrice.text()		//返利
		};
		//写入数据
		self.ant.set('_tmpSmartOrderPreview', { allData:allData, goodsList:goodsList });
		Loading.hide();
	};

	//每日优选：订单预览
	IdcWec.prototype.getOrderPreview = function(){
		var self = this;
		Loading.show('预览生成中...');
		var tmpCurrentPushGoods = self.getTmpCurrentPushGoods();				//所有选中的商品
		var $AllPushSku = self.$el.find('#AllPushSku');							//总商品数
		var $TotalPushPrice = self.$el.find('#TotalPushPrice');					//折扣价
		var $TotalPushPriceOG = self.$el.find('#TotalPushPriceOG');				//总价钱
		var $ReturnPrice = self.$el.find('#ReturnPrice');						//返利
		var $CumulativePrice = self.$el.find('#CumulativePrice');				//下次可返利
		var goodsList = [];
		var currentGoods = {};

		/*
		//循环读取商品明细
		//var $allPro = self.$el.find('#PushGoods .bd-cont li.user-selected .num');	//所有选中的商品
		$allPro.each(function(i,o){
			var orderItem = self.getItemData($(o));
			goodsList.push(orderItem);
		});
		*/

		//循环读取商品明细
		if(tmpCurrentPushGoods['date'] && tmpCurrentPushGoods['goodsList']){
			if(self.pushGoodsDate === tmpCurrentPushGoods.date){
				currentGoods = tmpCurrentPushGoods.goodsList;
			}
		}
		$.each(currentGoods, function(k,o){
			goodsList.push(o);
		});

		//生成订单信息
		var allData = {
			'allPushSku'		: $AllPushSku.text(),			//总商品数
			'totalPushPrice'	: $TotalPushPrice.text(),		//实付款
			'totalPushPriceOG'	: $TotalPushPriceOG.text(),		//订单总额
			'returnPrice'		: $ReturnPrice.text(),			//返利
			'cumulativePrice'	: $CumulativePrice.text()		//下次可返利
		};
		//写入数据
		self.ant.set('_tmpOrderPreview', { allData:allData, goodsList:goodsList });
		Loading.hide();
	};

	//自由订单：订单预览
	IdcWec.prototype.getIndependentOrderPreview = function(){
		var self = this;
		Loading.show('预览生成中...');
		var tigo = self.tmpIndependentGoodsOrder;
		var $IndependentOrderPreviewPrice = $body.find('#IndependentOrderPreviewPrice');
		//循环读取商品明细：对象转对象数组
		var goodsList = [];
		if(tigo['goodsList']){
			$.each(tigo.goodsList,function(k,o){
				var orderItem = {};
				if(o!=null){
					orderItem.goodsNo	= o.goodsNo;
					orderItem.goodsName = o.goodsName;
					orderItem.unit 		= o.unit;
					orderItem.spec 		= o.spec;
					orderItem.qty 		= o.qty;
					orderItem.stockQty 	= o.stockQty;
					orderItem.price 	= o.price;
					orderItem.disPrice 	= o.disPrice;
					orderItem.isProm    = o.isProm;
					orderItem.subtotal	= parseFloat(o.qty * o.disPrice).toFixed(2);
					goodsList.push(orderItem);
				}
			});
		}
		//生成订单信息
		var allData = {
			'allIndependentSku'		: goodsList.length,					//总商品数
			'totalIndependentPrice'	: self.$TotalIndependentPrice.text()		//实付款
		};
		$IndependentOrderPreviewPrice.text(self.$TotalIndependentPrice.text());
		//写入数据
		self.ant.set('_tmpIndependentOrderPreview', { allData:allData, goodsList:goodsList });
		Loading.hide();
	};

	//获取自由订单送货日期
	IdcWec.prototype.getIndependentDeliveryDate = function(){
		var date = new Date();
		var deliveryDate = date.getHours()<21 ? FnDate.getDirDate(1) : FnDate.getDirDate(2);
		return deliveryDate.date;
	};

	//智能订单：改变预览订单中的商品数量
	IdcWec.prototype.changeSmartOrderQty = function( $elm ){
		var self = this;
		if($elm && $elm.length){
			var qty = parseInt($elm.val());	//当前数量
			var max = parseInt($elm.attr('data-max'));	//商品数量上限
			var canChange = true;			//是否可进行变更
			if(!isNaN(qty)){
				if(qty > max){
					qty = max;
					$elm.val(qty);
					alert("促销商品只能购买"+max+"件");
				}else if(qty > 999){
					qty = 999;
					$elm.val(qty);
				} else if(qty <= 0) {
					qty = 0;
					if(!confirm('数量修改为0，是否确认删除该商品？')){
						canChange = false;
						$elm.val($elm.attr('data-qty'));
					}
				}
				if(canChange === true){
					var $LinkGoods = $body.find('#'+$elm.attr('data-ref'));					//目标商品
					var $LinkGoodsNum = $LinkGoods.find('.num');
					$elm.attr('data-qty', qty);
					$LinkGoodsNum.val(qty);
					if(qty > 0){
						$LinkGoods.addClass('user-selected');
						$LinkGoodsNum.removeAttr('disabled');
					} else {
						$LinkGoods.removeClass('user-selected');
						$LinkGoodsNum.attr('disabled','disabled');
					}
					//重新计算总价
					self.totalSmartOrderPrice();
					//重载预览界面
					self.getSmartOrderPreview();
				}
			} else {
				alert('商品数量必须为数字');
				$elm.val($elm.attr('data-qty'));
			}
		}
	};

	//每日优选：改变预览订单中的商品数量
	IdcWec.prototype.changePushGoodQty = function( $elm ){
		var self = this;
		if($elm && $elm.length){
			var qty = parseInt($elm.val());	//当前数量
			var max = parseInt($elm.attr('data-max'));	//商品数量上限
			var canChange = true;			//是否可进行变更
			if(!isNaN(qty)){
				if(qty > max){
					qty = max;
					$elm.val(qty);
					alert("促销商品只能购买"+max+"件");
				}else if(qty > 999){
					qty = 999;
					$elm.val(qty);
				} else if(qty <= 0) {
					qty = 0;
					if(!confirm('数量修改为0，是否确认删除该商品？')){
						canChange = false;
						$elm.val($elm.attr('data-qty'));
					}
				}
				if(canChange === true){
					var $LinkGoods = $body.find('#'+$elm.attr('data-ref'));					//目标商品
					var $LinkGoodsNum = $LinkGoods.find('.num');
					var oldQty = $elm.attr('data-qty');
					$elm.attr('data-qty', qty);
					$LinkGoodsNum.val(qty);
					if(qty > 0){
						$LinkGoods.addClass('user-selected');
						$LinkGoodsNum.removeAttr('disabled');
					} else {
						$LinkGoods.removeClass('user-selected');
						$LinkGoodsNum.attr('disabled','disabled');
					}
					var tmpCurrentPushGoods = self.getTmpCurrentPushGoods();				//所有选中的商品
					self.saveTmpCurrentPushGoods(false, $elm.attr('data-id'), qty);
					//重新计算总价
					self.totalPushPrice(function(price){
						//判断是否超出订单额度上限
						if(price > self.config.maxPrice){
							alert('单张订单金额上限为￥10000');
							self.totalPushPrice(false, self.saveTmpCurrentPushGoods(false, $elm.attr('data-id'), oldQty));
							$LinkGoodsNum.val(oldQty);
						}
					}, self.getTmpCurrentPushGoods());
					//重载预览界面
					self.getOrderPreview();
				}
			} else {
				alert('商品数量必须为数字');
				$elm.val($elm.attr('data-qty'));
			}
		}
	};

	//自由订单：改变预览订单中的商品数量
	IdcWec.prototype.changeIndependentGoodQty = function( $elm ){
		var self = this;
		if($elm && $elm.length){
			var qty = parseInt($elm.val());				//当前数量
			var max = parseInt($elm.attr('data-max'));	//商品数量上限
			var canChange = true;				//是否可进行变更
			if(!isNaN(qty)){
				if(qty > max){
					qty = max;
					$elm.val(qty);
					alert("库存不足只能购买"+max+"件");
				} else if(qty > 999){
					qty = 999;
					$elm.val(qty);
				} else if(qty <= 0) {
					qty = 0;
					if(!confirm('数量修改为0，是否确认删除该商品？')){
						canChange = false;
						$elm.val($elm.attr('data-qty'));
					}
				}
				if(canChange === true){
					var $IndependentOrderPreviewPrice = $body.find('#IndependentOrderPreviewPrice');
					var $LinkGoods = $body.find('#'+$elm.attr('data-ref'));					//目标商品
					var $LinkGoodsNum = $LinkGoods.find('.num');
					var id = $elm.attr('data-id');											//ID
					//重组商品价格
					var tigo = self.tmpIndependentGoodsOrder;
					var good = tigo.goodsList[id];
					good.qty = qty;
					$elm.attr('data-qty', qty);
					//重新计算总价
					var prices = self.totalIndependentPrice();
					$IndependentOrderPreviewPrice.text(prices.totalprice);
					$LinkGoodsNum.val(qty);
					if(qty > 0){
						$LinkGoods.addClass('user-selected');
						$LinkGoodsNum.removeAttr('disabled');
					} else {
						$LinkGoods.removeClass('user-selected');
						$LinkGoodsNum.attr('disabled','disabled');
						tigo.goodsList[id] = null;
					}
					//清除为0的商品
					var goodsList = {};
					var sku = 0;
					if(tigo['goodsList']){
						$.each(tigo.goodsList,function(k,o){
							var orderItem = {};
							if(o!=null){
								goodsList[k] = o;
								sku++;
							}
						});
					}
					self.tmpIndependentGoodsOrder.goodsList = goodsList;
					storage.set('_tmpIndependentGoodsOrder', self.tmpIndependentGoodsOrder);
					//重载预览界面
					self.$AllIndependentSku.text(sku);
					self.getIndependentOrderPreview();
				}
			} else {
				alert('商品数量必须为数字');
				$elm.val($elm.attr('data-qty'));
			}
		}
	};

	//智能订单：滚动到底部添加商品
	IdcWec.prototype.scrollAddSmartOrder = function( $elm, callback ){
		var self 		= this;
		var csol 		= self.currentSmartOrderList;		//智能订单信息
		var num 		= 10;								//单页加载商品数
		var page 		= parseInt($elm.attr('data-page'));	//当前页面
		var begin 		= num*page;							//开始的获取索引
		var goodsList 	= [];								//新商品列表
		callback 		= callback || function(){};
		if(!self.adding){
			self.adding = true;
			var typeId = $elm.attr('data-typeid');
			for(var i=0; i<csol.length; i++){
				if(csol[i].typeId === typeId){
					var o = csol[i];
					for(var i2=0; i2<10; i2++){
						if(o.goods[(begin+i2)]){
							goodsList.push(o.goods[(begin+i2)]);
						} else {
							break;
						}
					}
				}
			}
			//开始添加商品
			var $loading = $elm.find('.loading-data');
			if(goodsList.length>0){
				$loading.text('商品加载中...').removeClass('hide');
				//读取模版：自由订单商品列表（选项）
				var itemRender = ArtTemplate(tpl.smartOrderList.item);
		    	var itemHtml = itemRender({ data: goodsList });
				var $itemHtml = $(itemHtml);
				$itemHtml.appendTo($elm.find('ul'));
				$elm.attr('data-page',(page+1));
			} else {
				$loading.text('已经没有更多商品了').removeClass('hide');
			}
			callback();
			self.adding = false;
			return goodsList;
		}
	};

	//智能订单：自动添加剩余商品
	IdcWec.prototype.autoAddSmartOrder = function( callback ){
		var self 		= this;
		var csol 		= self.currentSmartOrderList;		//智能订单信息
		var begin 		= 10;								//开始添加的商品
		callback 		= callback || function(){};
		if(!self.adding){
			self.adding = true;
			var $bdCont = $body.find('#SmartOrder .bd-cont');
			//循环加载各类型的剩余商品
			$bdCont.each(function(i,o){
				var $cont = $(o);
				var typeId = $cont.attr('data-typeid');
				for(var i2=0; i2<csol.length; i2++){
					if(csol[i2].typeId === typeId){
						var goodsList 	= [];
						var goods = csol[i2].goods;
						if(goods.length > begin){
							for(var i3=0; i3<goods.length; i3++){
								if(goods[(begin+i3)]){
									goodsList.push(goods[(begin+i3)]);
								} else {
									break;
								}
							}
						}
						if(goodsList.length>0){
							//读取模版：自由订单商品列表（选项）
							var itemRender = ArtTemplate(tpl.smartOrderList.item);
					    	var itemHtml = itemRender({ data: goodsList });
							var $itemHtml = $(itemHtml);
							$itemHtml.appendTo($cont.find('ul'));
						}
					}
				}
			});
			callback();
			self.adding = false;
		}
	};

	//每日优选：滚动到底部添加商品
	IdcWec.prototype.scrollAddPushGoods = function( $elm, callback ){
		var self 		= this;
		var cpgl 		= self.currentPushGoodsList;		//每日优选信息
		var num 		= 10;								//单页加载商品数
		var page 		= parseInt($elm.attr('data-page'));	//当前页面
		var begin 		= num*page;							//开始的获取索引
		var goodsList 	= [];								//新商品列表
		callback 		= callback || function(){};
		if(!self.adding){
			self.adding = true;
			//判断当前商品列表是否有历史操作
			var currentGoods = null;
			var tmpCurrentPushGoods = self.getTmpCurrentPushGoods();
			if(tmpCurrentPushGoods['date'] && tmpCurrentPushGoods['goodsList']){
				if(self.pushGoodsDate === tmpCurrentPushGoods.date){
					currentGoods = tmpCurrentPushGoods.goodsList;
				}
			}
			var typeId = $elm.attr('data-typeid');
			for(var i=0; i<cpgl.length; i++){
				if(cpgl[i].typeId === typeId){
					var o = cpgl[i];
					for(var i2=0; i2<10; i2++){
						var nowGoods = o.goods[(begin+i2)];
						if(nowGoods){
							//判断当前列表中是否有选中商品
							if(currentGoods && currentGoods[nowGoods.id]){
								var cg = currentGoods[nowGoods.id];
								nowGoods.selected = true;
								nowGoods.qty = cg.qty;
							}
							goodsList.push(nowGoods);
						} else {
							break;
						}
					}
				}
			}

			//开始添加商品
			var $loading = $elm.find('.loading-data');
			if(goodsList.length>0){
				$loading.text('商品加载中...').removeClass('hide');
				//读取模版：自由订单商品列表（选项）
				var itemRender = ArtTemplate(tpl.pushGoodList.item);
		    	var itemHtml = itemRender({ data: goodsList });
				var $itemHtml = $(itemHtml);
				$itemHtml.appendTo($elm.find('ul'));
				$elm.attr('data-page',(page+1));
			} else {
				$loading.text('已经没有更多商品了').removeClass('hide');
			}
			callback();
			self.adding = false;
			return goodsList;
		}
	};

	//自由订单：滚动到底部添加商品
	IdcWec.prototype.scrollAddIndependentGoods = function( $elm, callback ){
		var self 		= this;
		var iogl 		= self.independentOrderGoodsList;	//自由订单信息
		var res 		= iogl.res;							//自由订单商品数
		var element 	= iogl.element;						//商品查询元素
		var num 		= 10;								//单页加载商品数
		var page 		= parseInt($elm.attr('data-page'));	//当前页面
		var begin 		= num*page;							//开始的获取索引
		var goodsList 	= [];								//新商品列表
		var gl 			= {rows:[]};						//新建商品列表
		callback 		= callback || function(){};
		if(!self.adding){
			self.adding = true;
			for(var i=0; i<num; i++){
				if(res.rows[(begin+i)]){
					gl.rows.push(res.rows[(begin+i)]);
				} else {
					break;
				}
			}
			goodsList = self.resetMallGoods(gl, element);
			//开始添加商品
			var $loading = $elm.find('.loading-data');
			if(goodsList.length>0){
				$loading.text('商品加载中...').removeClass('hide');
				//读取模版：自由订单商品列表（选项）
				var itemRender = ArtTemplate(tpl.independentOrderList.item);
		    	var itemHtml = itemRender({ data: goodsList });
				var $itemHtml = $(itemHtml);
				$itemHtml.appendTo($elm.find('ul'));
				$elm.attr('data-page',(page+1));
			} else {
				$loading.text('已经没有更多商品了').removeClass('hide');
			}
			callback();
			self.adding = false;
			return goodsList;
		}
	};

	//智能订单：改变门店商品库存显示
	IdcWec.prototype.checkGoodsStock = function(callback){
		var self = this;
		callback = callback || function(){};
		var shopId = self.config.userInfo.userId;
		IdcData.getStockByShop({ shopId:shopId },function(){},function(res){
			if(res['code'] && res.code == 2000){
				var goods = {};
				$.each(res.data || [],function(i,o){
					goods[o.goodsId] = o;
				});
				callback(goods);
			}
		});
	};



	//公用方法 ----------------------------------

	//获取一个商品对象的基础信息
	IdcWec.prototype.getItemData = function( $o ){
		//生成商品信息
		var orderItem = {};
		if($o && $o.length){
			orderItem.goodsNo	= $o.attr('data-id');
			orderItem.goodsName = $o.attr('data-goodsName');
			orderItem.unit 		= $o.attr('data-unit');		//单位
			orderItem.spec 		= $o.attr('data-spec');
			orderItem.maxQty 	= $o.attr('data-max');
			orderItem.stockQty 	= $o.attr('data-max');
			orderItem.isProm    = $o.attr('isProm');
			orderItem.qty 		= parseInt($o.val());	//商品数
			orderItem.price 	= parseFloat($o.attr('data-preprice')).toFixed(2);	//原价
			orderItem.disPrice 	= parseFloat($o.attr('data-price')).toFixed(2);		//折后价
			orderItem.subtotal	= parseFloat(orderItem.qty*orderItem.disPrice).toFixed(2);	//小计
			orderItem.imgUrl 	= $o.attr('data-imgurl');
		} else {
			orderItem = null;
		}
		return orderItem;
	};

	//判断订单是否过期
	IdcWec.prototype.isOverdue = function( date ){
		var self = this;
		var targetDay = FnDate.getAllDate(date);			//目标时间
		var overdue = FnDate.getAllDate(self.overdue);		//预设的过期时间
		var prevTime = FnDate.getDirDate(self.config.dryDay, overdue.date);	//早于3天的判断时间
		//如果时间为17点以后，或3天之前，都为过期订单
		var isOverdue = (targetDay>overdue.allDate || targetDay.allDate<prevTime.allDate) ? true : false;
		return isOverdue;
	}

	//获取优惠信息
	IdcWec.prototype.getDiscount = function(info, callback ){
		var self = this;
		self.isLogined(function(userInfo){
			callback = callback || function(){};
			//获取优惠信息
			IdcData.getDiscount({ shopId: self.config.userInfo.userId, date:info.query.date || self.pushGoodsDate },function(){},function(res){
				self.discountInfo = res.data!=null ? res.data[0] : {flag:0, lastAmount:0, curAmount:0};
				callback();
			});
		});
	}

	//新注册用户获取每日优选的时间倒计时
	IdcWec.prototype.orderCountdown = function( time ){
		var self = this;
		time = time || self.config.userInfo.userRegisterDay;
		if(typeof time === 'string'){ time = time.replace(/-/g,'/'); }
		//var time = '2016/3/1 02:28:50';
		var today = new Date(IdcData.getServerTime());
		var ust = new Date(time);
		//如果为新注册用户，则计算获取时间
		if(today.toLocaleDateString() == ust.toLocaleDateString()){
			var dateStr = '';
			var newH = ust.getHours();
			var um = ust.getMinutes();
			if(newH>9){
				if(newH==23){
					ust = new Date((ust/1000+86400)*1000);
				}
			} else {
				newH = '0'+newH;
			}
			var newD = ust.toLocaleDateString();
			//10到40区间
			if(um>=10 && um<40){
				dateStr = newD+' '+newH+':40:00';
			} else 
			//40到00区间
			if(um>=40){
				newH = parseInt(newH) + 1;
				newH = newH>9 ? (newH<24?newH:'00') : '0'+newH;
				dateStr = newD+' '+newH+':10:00';
			} else 
			//0到10区间
			if(um>=0 && um<10){
				dateStr = newD+' '+newH+':10:00';
			}
			//console.log('刷新时间：'+dateStr);
			//console.log('注册时间：'+time);

			window.dateStr = dateStr;
			window.userReload = 0;
			var $msg = $body.find('#PushGoodsErrMsg');
			var cd = function(){
				var ts = (new Date(window.dateStr)) - (new Date());
                var mm = parseInt(ts / 1000 / 60 % 60, 10);
                var ss = parseInt(ts / 1000 % 60, 10);
                mm = mm<10 ? '0'+mm : mm;
                ss = ss<10 ? '0'+ss : ss;
				$msg.html('请稍候，iDC系统正在为您生成<br>每日优选商品清单，还需00:'+mm+':'+ss);
				if(mm>0 || ss>0){
					setTimeout(function(){
						cd();
					},1000);
				} else {
					$msg.html('已到生成时间，如还没有出现<br>每日优选商品。请点击“<a href="javascript:location.reload();">此处刷新</a>”');
					if(window.userReload==0){
						window.userReload = 1;
						location.href = '#PushGoods';
					}
				}
			};
			cd();
		}
	};

	//回退操作
	IdcWec.prototype.back = function( $elm ){
		if(typeof $elm === 'object'){
			var gotoPage = $elm.attr('data-gotoPage');
			var isOne = $elm.attr('data-isOne');
			//判断是否有跳转目标
			if(gotoPage && gotoPage!=''){
				//判断是否为只跳一次
				if(isOne && gotoPage=='true'){
					$elm.removeAttr('data-isOne');
				}
				$elm.removeAttr('data-gotoPage');
				location.href = gotoPage;
			} else {
				window.history.back(-1);
			}
		} else {
			window.history.back(-1);
		}
	};

	//IDC：显示提示信息
	IdcWec.prototype.showMessage = function( type ){
		var self = this;
		type = type || 'FirstMessage';
		//是否为第一版
		if(type === 'FirstMessage'){
			if(self.isShowFirstMessage==true){
				self.isShowFirstMessage = false;
				self.showCoverBox('#FirstMessage');
				/* 	取消计时形式
				var _showFirstMessage = storage.get('_showFirstMessage');
				var serverTime = IdcData.getServerTime();
				var allDate = FnDate.getAllDate(serverTime);
				var stu = false;
				if(!_showFirstMessage || _showFirstMessage==null || _showFirstMessage=='null'){
					stu = true;
				} else {
					if(_showFirstMessage.date != allDate.date){
						stu = true;
					}
				}
				if(stu){
					//显示提示信息
					self.showCoverBox('#FirstMessage');
					storage.set('_showFirstMessage', { date:allDate.date, num:1 });
				}
				*/
			}
		} else if(type === 'FirstIndependentMessage'){
			if(self.isShowFirstIndependentMessage==true){
				self.isShowFirstIndependentMessage = false;
				self.showCoverBox('#FirstIndependentMessage');
			}
		}
	};

	//显示弹层
	IdcWec.prototype.showCoverBox = function( element, callback, noShowBg ){
		var self = this;
		callback = callback || function(){};
		noShowBg = noShowBg==true ? true : false;
		var $SlideCoverBg = self.$el.find('.slide-cover-bg');
		var $SlideCoverBox = self.$el.find(element);
		$SlideCoverBg.addClass('show');
		if(noShowBg != true){
			$SlideCoverBox.addClass('show');
		}
		callback();
	};
	//隐藏弹层
	IdcWec.prototype.hideCoverBox = function( element, callback, noHideBg ){
		var self = this;
		callback = callback || function(){};
		noHideBg = noHideBg==true ? true : false;
		var $SlideCoverBg = self.$el.find('.slide-cover-bg');
		var $SlideCoverBox = self.$el.find(element);
		$SlideCoverBg.removeClass('show');
		if(noHideBg != true){
			$SlideCoverBox.removeClass('show');
		}
		callback();
	};


	//生成加载中方法
	IdcWec.prototype.buildLoading = function(){
		var self = this;
		self.loading = {
			//显示内容：如果没有自定义内容，则显示默认信息：内容加载中
			show: function( html, isCont ){
				var isDef = true;
				self.ant.set('showLoading',true);
				if(typeof html==='string' && isCont!==true){
					isDef = true;
					self.$el.find('.loading .icon-loading').html(html);
				} else if(typeof html==='string' && isCont===true){
					isDef = false;
					self.$el.find('.loading .content').html(html);
				} else {
					isDef = true;
					self.$el.find('.loading .icon-loading').html('内容加载中...');
				}
				self.ant.set('loadingDef',isDef);
			},
			//隐藏加载中内容
			hide: function( seconds, callback ){
				callback = callback || function(){};
				seconds = !seconds && seconds<0 ? 500 : seconds;
				setTimeout(function(){
					self.ant.set('showLoading',false);
					callback();
				},seconds);
			}
		};
		return self.loading;
	};

	//初始化日期插件
	IdcWec.prototype.initSelectDate = function(){
		var self = this;
		var $SelectDateInput = self.$el.find('#SelectDateInput');
		$SelectDateInput.calendar({
            controlId:'divDate',
            speed:0,
            notHide:true,
            father:'#SelectDate .view-box-container',
            callback:function(){
            	//隐藏选择框
				self.hideCoverBox('.select-date');
                location.href = '#PushGoods?date=' + $SelectDateInput.val();
            }
        });
	};

	//初始化日期插件：智能订单
	IdcWec.prototype.initSmartSelectDate = function(){
		var self = this;
		var $SmartSelectDateInput = self.$el.find('#SmartSelectDateInput');
		$SmartSelectDateInput.calendar({
            controlId:'divDateSmart',
            speed:0,
            notHide:true,
            father:'#SmartSelectDate .view-box-container',
            callback:function(){
            	//隐藏选择框
				self.hideCoverBox('.smart-select-date');
                location.href = '#SmartOrder?date=' + $SmartSelectDateInput.val();
            }
        });
	};

//== 监听事件和生成 =========================================================
	//监听事件
	IdcWec.prototype.watch = function(){
		var self = this;
		var $el = self.$el;
		//用户登录
		$body.on('submit','#UserLogin',function(){
			self.login();
		})
		//注销用户
		.on('click','#LogOut',function(){
			self.logout();
		})
		//重设所有后退按钮
		.on('click','a[href="#back"]',function(){
			self.back($(this));
			return false;
		})
		//从 welcome 点击进入每日优选
		.on('click','#Welcome .go-to-push-goods',function(){
			self.isShowFirstMessage = true;
		})
		//从 welcome 点击进入自由订单
		.on('click','#Welcome .go-to-independent-order',function(){
			self.isShowFirstIndependentMessage = true;
		})
		//增加商品数
		.on('click','.buy .add',function(){
			var $this = $(this);
			var $li = $this.parent().parent().parent();
			//判断当前状态是否为可点击
			if($li.attr('data-state')=='true'){
				var $num = $this.parent().find('.num');
				$num.attr('data-qty',$num.val());
				//var $linkGoods = $body.find('#'+$li.attr('data-ref'));
				//var $linkGoodsNum = $body.find('#'+$num.attr('data-ref'));
				//if(!$num.attr('disabled')){
					var val = parseInt($num.val());
				    var max = parseInt($this.attr('data-max'));
					if(val<$num.attr('data-max') && val<999){
						//var $recom = $this.parent().prev();
						//$recom.removeClass('hide');	//显示推荐数量
						$num.val(val+1);
						//$linkGoodsNum.val(val+1);
					}
				    if(val >= max){
						var goodType = $this.attr('data-goodtype');
						switch(goodType){
							//计算推送订单总价：原始推送商品
							case 'og': alert("促销商品，最多只能购买"+max+"件"); break;
							case 'independent':
								alert("库存不足，最多只能购买"+max+"件");
								break;
						}
						return;
					}
					$li.addClass('user-selected');
					//$linkGoods.addClass('user-selected');
					$num.removeAttr('disabled');
					//$linkGoodsNum.removeAttr('disabled');
					self.changeChecked($this, 1);
				//}
			}
		})
		//减少商品数
		.on('click','.buy .reduce',function(){
			var $this = $(this);
			var $li = $this.parent().parent().parent();
			//判断当前状态是否为可点击
			if($li.attr('data-state')=='true'){
				var $num = $this.parent().find('.num');
				$num.attr('data-qty',$num.val());
				//var $linkGoods = $body.find('#'+$li.attr('data-ref'));
				//var $linkGoodsNum = $body.find('#'+$num.attr('data-ref'));
				//if(!$num.attr('disabled')){
					var val = parseInt($num.val());
					if(val>0){
						//var $recom = $this.parent().prev();
						//$recom.removeClass('hide');	//显示推荐数量
						$num.val(val-1);
						//$linkGoodsNum.val(val-1);
						//是否为0
						if((val-1) == 0){
							$li.removeClass('user-selected');
							//$linkGoods.removeClass('user-selected');
							$num.attr('disabled','true');
							//$linkGoodsNum.attr('disabled','true');
						} else {
							$li.addClass('user-selected');
							//$linkGoods.addClass('user-selected');
							$num.removeAttr('disabled');
							//$linkGoodsNum.removeAttr('disabled');
						}
					}
					self.changeChecked($this);
				//}
			}
		})
		//选中商品
		.on('click','.photo',function(){
			var $li = $(this).parent();
			//var $linkGoods = $body.find('#'+$li.attr('data-ref'));
			//是否为非选中状态
			if(!$li.hasClass('user-selected')){
				//判断当前状态是否为可点击
				if($li.attr('data-state')=='true'){
					var $liNum = $li.addClass('user-selected').find('.num');
					//var $linkGoodsNum = $linkGoods.addClass('user-selected').find('.num');
					$liNum.removeAttr('disabled');
					//$linkGoodsNum.removeAttr('disabled');
					//如果数量为0则添加为1
					if($liNum.val()==0 /*|| $linkGoodsNum.val()==0*/){
						$liNum.val(1);
						//$linkGoodsNum.val(1);
					}
				}
			} else {
				$li.removeClass('user-selected').find('.num').attr('disabled','true');
				//$linkGoods.removeClass('user-selected').find('.num').attr('disabled','true');
			}
			self.changeChecked($(this), 2);
		})


		// -- 智能订单 -----------------------------
		//智能订单：前一天
		.on('click','.smart-order-date .date-title .prev',function(){
			self.getSmartPrevNextOrder('prev');
		})
		//智能订单：下一天
		.on('click','.smart-order-date .date-title .next',function(){
			self.getSmartPrevNextOrder('next');
		})
		//每日优选：展示日期选择
		.on('click','.smart-order-date .date-title .date',function(){
			self.showSmartSelectDate();
		})
		//每日优选：关闭日期选择
		.on('click','.smart-select-date .close',function(){
			self.hideCoverBox('.smart-select-date');
		})
		//智能订单：显示订单预览
		.on('click','#ShowSmartOrderPreview',function(){
			self.getSmartOrderPreview();
			self.showCoverBox('#SmartOrderPreview');
		})
		//智能订单：关闭订单预览
		.on('click','#HideSmartOrderPreview',function(){
			self.hideCoverBox('#SmartOrderPreview');
		})
		//智能订单：修改订单预览商品数量
		.on('change','#SmartOrderPreview .no-input',function(){
			self.changeSmartOrderQty($(this));
		})
		//智能订单：确认订单
		.on('click','#SmartOrderSubmit',function(){
			var $this = $(this);
			if(!$this.hasClass('disabled')){
				self.smartOrderSubmit();
			}
		})
		//智能订单：提交订单
		.on('click','#SendSmartOrder',function(){
			self.sendSmartOrder();
		})


		// -- 每日优选 -----------------------------
		//每日优选：前一天
		.on('click','.push-goods-date .date-title .prev',function(){
			self.getPrevNextOrder('prev');
		})
		//每日优选：下一天
		.on('click','.push-goods-date .date-title .next',function(){
			self.getPrevNextOrder('next');
		})
		//每日优选：展示日期选择
		.on('click','.push-goods-date .date-title .date',function(){
			self.showSelectDate();
		})
		//每日优选：关闭日期选择
		.on('click','.select-date .close',function(){
			self.hideCoverBox('.select-date');
		})
		//每日优选：展示升级进货单
		.on('click','.update-goods-btn',function(){
			self.loadRecommendGoods();
		})
		//每日优选：关闭升级进货单
		.on('click','.update-push-goods .close',function(){
			self.hideCoverBox('.update-push-goods');
		})
		//IDC：关闭第一次显示的信息框
		.on('click','.first-message .close-btn',function(){
			var $this = $(this);
			self.hideCoverBox('.first-message', function(){
				var reopen = $this.attr('data-reopen');
				if(reopen && reopen!=''){
					self.showCoverBox(reopen,function(){
						$this.attr('data-reopen','');
					});
				}
			});
		})
		//点击商品类型显示对应内容框
		.on('click','.goods-list-box .goods-type a',function(){
			var $this = $(this);
			var $li = $this.parent();
			var $GoodsListBox = $this.parents('.goods-list-box');
			if(!$li.hasClass('current')){
				//判断是否要转换版块
				if(!$this.attr('data-nochange') || $this.attr('data-nochange')=='false'){
					var idx = $this.attr('data-index');
					$GoodsListBox.find('.current').removeClass('current');
					$li.addClass('current');
					$GoodsListBox.find('.bd-cont:eq('+idx+')').addClass('current');
				} else {
					$GoodsListBox.find('li.current').removeClass('current');
					$li.addClass('current');
				}
				//判断是否需要执行操作
				var run = $this.attr('data-run');
				if(run && run!=''){
					if(run === 'independent'){
						self.getMallGoods({ catNo: $this.attr('data-typeid') },function(){},function(){
							//内容框返回顶部
							var $bdCont = self.$el.find('#IndependentOrder .bd-cont');
							$bdCont.scrollTop(0);
						});
					} else if(run === 'pushGoods'){
						//内容框返回顶部
						//var $bdCont = self.$el.find('#PushGoods .current');
						//$bdCont.scrollTop(1);
					}
				}
			} else {
				return;
			}
		})
		//每日优选：添加推荐商品到推送订单中
		.on('click','#NowUpdatePushGoods',function(){
			self.addMoreGoods();
		})
		//每日优选：确认订单
		.on('click','#PushGoodsSubmit',function(){
			var $this = $(this);
			if(!$this.hasClass('disabled')){
				self.pushGoodsSubmit();
			}
		})
		//每日优选：提交订单
		.on('click','#SendOrder',function(){
			self.sendPushGoodsOrder();
		})
		//每日优选：显示订单预览
		.on('click','#ShowOrderPreview',function(){
			self.getOrderPreview();
			self.showCoverBox('#OrderPreview');
		})
		//每日优选：关闭订单预览
		.on('click','#HideOrderPreview',function(){
			self.hideCoverBox('#OrderPreview');
		})
		//每日优选：修改订单预览商品数量
		.on('change','#OrderPreview .no-input',function(){
			self.changePushGoodQty($(this));
		})
		//每日优选：显示促销返利
		.on('click','#ShowReturnPrice',function(){
			var $closeBtn = self.$el.find('#FirstMessage .close-btn');
			$closeBtn.attr('data-reopen','#OrderPreview');
			self.hideCoverBox('#OrderPreview',function(){
				self.showCoverBox('#FirstMessage');
			});
		})
		//每日优选：显示促销信息
		.on('click','.show-return-price',function(){
			self.showCoverBox('#FirstMessage');
		})


		// -- 自由订单 -----------------------------
		//自由订单：显示购物车
		.on('click','#ShowShoppingCar',function(){
			self.getIndependentOrderPreview();
			self.showCoverBox('#IndependentOrderPreview');
		})
		//自由订单：隐藏购物车
		.on('click','#HideIndependentOrderPreview',function(){
			self.hideCoverBox('#IndependentOrderPreview');
		})
		//自由订单：修改订单预览商品数量
		.on('change','#IndependentOrderPreview .no-input',function(){
			self.changeIndependentGoodQty($(this));
		})
		//自由订单：搜索商品
		.on('click','#SearchIndependentGoods .now-search', function(){
			var searchText = self.$el.find('#SearchIndependentText').val();
			var catNo = self.$el.find('#NowSearchType').attr('data-typeid');
			self.searchMallGoods({ catNo:catNo, goodsName:searchText });
		})
		//自由订单：搜索商品－点击选择搜索分类
		.on('click','#SearchIndependentGoods .search-type li a',function(){
			var $this = $(this);
			var $NowSearchType = $body.find('#NowSearchType');
			$NowSearchType.attr('data-typeid', $this.attr('data-typeid')).text($this.text());
		})
		//自由订单：添加搜索商品到购物车
		.on('click','#AddToIndependentGoods',function(){
			var $this = $(this);
			if(!$this.hasClass('disabled')){
				self.addToIndependentGoods();
			}
		})
		//自由订单：显示搜索框
		.on('click','#ShowSearchIndependentGoods',function(){
			self.showSearchIndependentGoods();
		})
		//自由订单：隐藏搜索框
		.on('click','#SearchIndependentGoods .btn-close',function(){
			self.hideSearchIndependentGoods();
		})
		//自由订单：点击搜索关键字进行搜索
		.on('click','#SearchIndependentGoods .history-list a', function(){
			var $this = $(this);
			var searchText = $this.text();
			var catNo = $this.attr('data-typeid');
			self.searchMallGoods({ catNo:catNo, goodsName:searchText });
		})
		//自由订单：清空搜索关键字
		.on('click','#EmptySearchHistory',function(){
			self.emptySearchHistory();
		})
		//自由订单：确认订单
		.on('click','#IndependentOrderSubmit',function(){
			var $this = $(this);
			if(!$this.hasClass('disabled')){
				self.independentOrderSubmit();
			}
		})
		//自由订单：提交订单
		.on('click','#SendIndependentOrder',function(){
			self.sendIndependentGoodsOrder();
		})
		//自由订单：剩余效期选择
		.on('click','.month-time-list-box a',function(){
			var $this = $(this);
			var time = $this.attr('data-time');
			var $MonthTime = $body.find('#MonthTime');
			$MonthTime.text($this.text());
			self.getTimeMallGoods({ month:time });
		})


		// -- 其他 -------------------------------
		//查看商品清单：来自“智能订单：确认订单”
		.on('click','#SubmitSmartOrder .goto-goods-item-desc',function(){
			Loading.show();
			Loading.hide(0,function(){
				location.href = '#OrderListing?form=SubmitSmartOrder';
			});
		})
		//查看商品清单：来自“每日优选：确认订单”
		.on('click','#SubmitOrder .goto-goods-item-desc',function(){
			Loading.show();
			Loading.hide(0,function(){
				location.href = '#OrderListing?form=SubmitOrder';
			});
		})
		//查看商品清单：来自“自由订单：确认订单”
		.on('click','#SubmitIndependentOrder .goto-goods-item-desc',function(){
			Loading.show();
			Loading.hide(0,function(){
				location.href = '#OrderListing?form=SubmitIndependentOrder';
			});
		})
		//查看商品清单：来自“智能订单－已有订单”
		.on('click','#HaveSmartOrder .goto-goods-item-desc',function(){
			Loading.show();
			Loading.hide(0,function(){
				location.href = '#OrderListing?form=HaveSmartOrder';
			});
		})
		//查看商品清单：来自“每日优选－已有订单”
		.on('click','#HaveOrder .goto-goods-item-desc',function(){
			Loading.show();
			Loading.hide(0,function(){
				location.href = '#OrderListing?form=HaveOrder';
			});
		})
		//查看商品清单：来自“订单详情”
		.on('click','#OrdersDesc .goto-goods-item-desc',function(){
			Loading.show();
			Loading.hide(0,function(){
				location.href = '#OrderListing?form=OrdersDesc&orderId='+$(this).attr('data-orderId');
			});
		})
		//取消订单
		.on('click','.cancel-order',function(){
			var $this = $(this);
			if(confirm('是否取消订单')){
				var orderId = $this.attr('data-orderId');
				var devDay = $this.attr('data-devDay');
				var form = $this.attr('data-form');
				//判断来源
				switch(form){
					//订单详情
					case 'OrdersDesc': break;
					//每日优选
					case 'HaveOrder': self.cancelRecommendedOrder(orderId, devDay); break;
					//智能订单
					case 'HaveSmartOrder': self.cancelSmartOrder(orderId, devDay); break;
				}
			}
		})
		//支付订单
		.on('click','.pay-order',function(){
			var $this = $(this);
			var orderId = $this.attr('data-orderId');
			var devDay = $this.attr('data-devDay');
			var form = $this.attr('data-form');
			var price = $this.attr('data-price');
			//判断来源
			location.href='#Pay?orderId='+orderId+'&price='+price+'&form='+form+'&devDay='+devDay;
		})
		//支付方式选择转换处理
		.on('click','.radio-inline input[type="radio"]',function(){
			var $this = $(this);
			var $text = $body.find('#'+$this.attr('data-fid')+' .'+$this.attr('data-rel'));
			if($this.val()=='SMW6'){
				$text.text('去支付');
			} else {
				$text.text('提交订单');
			}
		})
		//选择支付方式
		.on('click','.pay-select li',function(){
			var $this = $(this);
			var $paySelect = $this.parent();
			if(!$this.hasClass('selected')){
				$paySelect.find('.selected').removeClass('selected');
				$this.addClass('selected');
			}
		})
		//确认支付：支付订单
		.on('click','#NowPayGo',function(){
			$this = $(this);
			var $selected = $body.find('#WebPay .pay-select .selected');
			var price = $this.attr('data-price');
			var orderId = $this.attr('data-orderid');
			var paytype = $selected.attr('data-paytype');
			//微信支付方式
			if(paytype === 'SMW6'){
				location.href = '#Pay?orderId='+orderId+'&price='+price;
			}
			return false;
		})
		.on('click','#indepenTips',function(){
				var $this = $(this);

				var temp = $body.find('#IndependentOrder .view-box-container');
				var tep = $body.find('#IndependentOrder .month-time');
				var orderList = $body.find('#OrderListing .view-box-container');
				if(temp.length> 0){
					temp.removeAttr('style');
				}
				if(tep.length > 0){
					tep.removeAttr('style');
				}
				if(orderList.length > 0){
					orderList.removeAttr('style');
				}
				/*var topOffset = "51px";
				if(tep.length >0){
					topOffset = '100px'
				}

				temp.css({'top':topOffset});
*/
				$this.hide();
				//$body.find('#IndependentOrder .view-box-container').css('top','')
		});
	};

	//生成并初始化
	IdcWec.prototype.init = function(callback){
		var self = this;
		callback = callback || function(){};
		Template.load('./tpl/dist/idc/main.html', function(html) {
			var $tpl = $(html);
			self.$el = $($tpl.html());
			self.ant = new Template(self.$el);
			self.$el.appendTo($body);

			//-- 生成方法 ---------------------------
			//生成日期方法
			FnDate = Idc.fnDate();
			//生成加载中
			Loading = self.buildLoading();
			//初始化“每日优选”日期
			self.initSelectDate();
			//初始化“智能订单”日期
			self.initSmartSelectDate();

			//-- 写入预参数 ---------------------------
			var pushGoodsDate = FnDate.getDirDate(self.config.dryDay);
			var smartOrderDate = FnDate.getDirDate(self.config.dryDay);
			//每日优选：重新设置初始日期
			self.pushGoodsDate = pushGoodsDate.date;
			//智能推送：重新设置初始日期
			self.smartOrderDate = smartOrderDate.date;
			//智能推送：日期
			self.ant.set('smartOrderDate', smartOrderDate);
			//每日优选：日期
			self.ant.set('pushGoodsDate', pushGoodsDate);
			//确认订单：未完成的订单	（推送订单）
			self.ant.set('tmpPushGoodsOrder', storage.get('_tmpPushGoodsOrder') || []);
			//确认订单：未完成的订单（自由订单）
			self.ant.set('tmpIndependentGoodsOrder', storage.get('_tmpIndependentGoodsOrderList') || []);
			//订单列表
			self.ant.set('ordersDesc', false);
			//默认折扣
			self.ant.set('pushGoodsDiscount', 1);
			//是否可提交订单
			self.ant.set('canSubmitPushGoods', true);
			//是否可升级进货单
			self.ant.set('canUpdatePushGoods', true);

			//支付信息为空
			self.ant.set('payInfo', null);

			//-- 临时参数 ---------------------------
			//自由订单搜索
			self.ant.set('searchGoodsList', false);
			
			//-- 监听事件 --------------------------------
			//设置版块并加载
			self.setPage();
			//绑定事件
			self.watch();

			//回调函数
			callback(self);
		});
	};

	return IdcWec;
});